“& ="是什么意思在此C#代码中做什么? [英] What does the "&=" in this C# code do?

查看:44
本文介绍了“& ="是什么意思在此C#代码中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些看起来像这样的代码:

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.

与以下相同:

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

您通常会看到快捷键和运算符&& ,但是将运算符& 应用于布尔值时,它也是and运算符,只有它不会t做捷径.

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.

您可以改用&& 运算符(但没有& == 运算符)来节省一些计算.如果 someBoolean 包含 false ,则不会计算第二个操作数:

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

在特殊情况下,变量在前面的行中设置为 true ,因此and操作完全不需要.您可以只计算表达式并将其分配给变量.另外,除了转换字符串然后进行比较之外,您应该使用一个比较方法来处理您希望进行比较的方式:

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

这篇关于“& ="是什么意思在此C#代码中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆