开发者

Why does _ret evaluate to true, shouldn't it evaluate to false (Bit Operator)?

class Program
{
    private static bool _ret = true;

    static void Main()
    {
        _ret &= Method();
        Console.WriteLine(_ret);
        Console.Read();
    }

    private static bool Method()
    {
        _ret &= false;
        return true;
    }
}

We开发者_如何学Go came across this issue in a larger application we are developing and was wondering if it was expected functionality? This is written in c# with Visual Studio 2010


As explained by Eric Lippert in his blog post "Precedence vs Associativity vs Order",

The expression F() + G() * H() is equivalent to F() + (G() * H()), but C# does NOT evaluate G() * H() before F(). Rather, this is equivalent to:

temp1 = F();

temp2 = G();

temp3 = H();

temp4 = temp2 * temp3;

result = temp1 + temp4;

So in your case, it evaluates _ret prior to calling Method(), and the fact that _ret changes inside Method() does not affect the outer call.

See: http://blogs.msdn.com/b/ericlippert/archive/2008/05/23/precedence-vs-associativity-vs-order.aspx


My bet is that _ret &= Method() is translated to _ret = _ret & Method() and the _ret on the RHS is being evaluated before Method() is called.

Since _ret is true initially, it's true when it evaluates _ret in the RHS, and then _ret is changed to false in Method(), but that doesn't matter since Method() returns true and true & true = true.

This is probably compiler/environment specific... it relies on left-to-right evaluation, which you shouldn't count on.


Your method return shoule be like below

    private static bool Method() 
    {
        return _ret &= false; 
    } 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜