简体   繁体   中英

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

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 "="?

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);

对于&运算符,它相当于+=

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

在这种情况下,在someBoolean为true之前,意味着

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

It is short for:

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

See MSDN (&= operator).

这是简短的形式:

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

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM