What does the “&=” in this C# code do?

≡放荡痞女 提交于 2019-12-21 07:55:53

问题


I came across some code that looks like this:

string someString;

...

bool someBoolean = true;
someBoolean &= someString.ToUpperInvariant().Equals("blah");

Why would I use the bitwise operator instead of "="?


回答1:


It's not a bitwise operator when it's applied to boolean operators.

It's the same as:

someBoolean = someBoolean & someString.ToUpperInvariant().Equals("blah");

You usually see the short-cut and operator &&, but the operator & is also an and operator when applied to booleans, only it doesn't do the short-cut bit.

You can use the && operator instead (but there is no &&= operator) to possibly save on some calculations. If the someBoolean contains false, the second operand will not be evaluated:

someBoolean = someBoolean && someString.ToUpperInvariant().Equals("blah");

In your special case, the variable is set to true on the line before, so the and operation is completely unneccesary. You can just evaluate the expression and assign to the variable. Also, instead of converting the string and then comparing, you should use a comparison that handles the way you want it compared:

bool someBoolean =
  "blah".Equals(someString, StringComparison.InvariantCultureIgnoreCase);



回答2:


It's the equivalent of += for the & operator.




回答3:


someBoolean = someBoolean & someString.ToUpperInvariant().Equals("blah");

which, in this case, before someBoolean is true, means

someBoolean = someString.ToUpperInvariant().Equals("blah");



回答4:


It is short for:

someBoolean = someBoolean & someString.ToUpperInvariant().Equals("blah");

See MSDN (&= operator).




回答5:


It is the short form of this:

someBoolean = someBoolean & someString.ToUpperInvariant().Equals("blah")



回答6:


As Guffa pointed, there IS a difference between & and &&. I would not say you can, but rather you SHOULD use && instead of & : & makes your code geeker, but && makes your code more readable... and more performant. The following shows how :

class Program
{
    static void Main(string[] args)
    {
        Stopwatch Chrono = Stopwatch.StartNew();
        if (false & Verifier())
            Console.WriteLine("OK");
        Chrono.Stop();
        Console.WriteLine(Chrono.Elapsed);

        Chrono.Restart();
        if (false && Verifier())
            Console.WriteLine("OK");
        Chrono.Stop();
        Console.WriteLine(Chrono.Elapsed);
    }

    public static bool Verifier()
    {
        // Long test
        Thread.Sleep(2000);
        return true;
    }
}


来源:https://stackoverflow.com/questions/4556027/what-does-the-in-this-c-sharp-code-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!