简体   繁体   English

C#按位相等的bool运算符

[英]C# bitwise equal bool operator

Boolean in C# are 1 byte variables. C#中的布尔值是1个字节的变量。 And because bool are shortcuts for the Boolean class, I would expect that the &= , |= operations have been overridden to let them work with the boolean types but I'm not so sure about it. 并且因为bool是Boolean类的快捷方式,我希望覆盖&=| =操作以使它们使用布尔类型,但我不太确定它。 There is nothing like &&= or ||= to be used. 没有像&& =|| =那样的东西。

Here's my question, doing something like: 这是我的问题,做的事情如下:

bool result = condition;
result &= condition1;
result &= condition2;

will work but is it just because the bool will be 00000000 for false and 00000001 for true or because underneath the bool class will use something like &&= and ||= when the previous are called? 会工作,但这只是因为bool将为00000000表示false00000001表示true或者因为bool类下面会使用类似&& =|| =的东西来调用前一个? Is it actually safe to use the previous notations or is better to use 使用以前的符号实际上是安全的还是更好用

bool result = condition;
result = result && condition1;
result = result && condition2;

to avoid any strange behavior? 避免任何奇怪的行为?

Please note that conditions could be something like A >= B or any other possible check that will return a bool. 请注意,条件可能类似于A> = B或任何其他可能会返回bool的检查。

As far as I can read in this SO post , the only real difference between bitwise operators and logical operators on booleans is that the latter won't evaluate the right side operand if the left side operand is false . 至于我在这篇SO帖子中可以看到,布线运算符和布尔运算符逻辑运算符之间唯一真正的区别在于,如果左侧操作数为false ,则后者不会评估右侧操作数。

That means that if you have two booleans, there won't be much difference. 这意味着如果你有两个布尔值,那就不会有太大差别了。 If you have two methods, the last one doesn't get executed using logical operators, but it does with binary operators. 如果你有两个方法,最后一个方法不会使用逻辑运算符执行,但它使用二元运算符。

Per the documentation (emphasis mine): 根据文件 (强调我的):

An expression using the &= assignment operator, such as 使用&=赋值运算符的表达式,例如

x &= y

is equivalent to 相当于

x = x & y

except that x is only evaluated once. 除了x只评估一次。 The & operator performs a bitwise logical AND operation on integral operands and logical AND on bool operands . &运算符对积分操作数和bool操作数上的逻辑AND 执行按位逻辑AND 运算

And similar for |= . |=类似

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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