我只是注意到按位运算不如逻辑“与\或”运算那么“智能”,我想知道为什么?
这是一个例子:
// For the record
private bool getTrue(){return true;}
private bool getFalse(){return false;}
// Since a is true it wont enter getFalse.
bool a = getTrue() || getFalse();
// Since a is false it wont enter getTrue.
bool b = getFalse() && getTrue();
// Since b is false it wont enter getTrue.
b = b && getTrue();
但是位运算符“|=”和“&=”并不那么聪明:
bool a = getTrue();
a |= getFalse(); // a has no chance to get false but it still enters the function.
a = getFalse();
a &= getTrue(); // a has no chance to get true but still performs this operation.
我想知道为什么它们不以相同的逻辑方式工作。
最佳答案
一个澄清:
运算符 &=
和 |=
在 bool
上计算时不是按位运算符 - 它们是逻辑运算符,但它们是相当于 x = x & y
和 x = x | y
,它不会像 &&
和 ||
那样短路。
来自 MSDN :
The & operator performs a bitwise logical AND operation on integral operands and logical AND on bool operands.
设计者本可以实现||=
和&&=
,但由于它们仅是合适的对于 bool 类型,那里没有太多值(value)。
关于c# - 为什么按位运算符不如逻辑 "and\or"运算符聪明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23634610/