c# - 为什么按位运算符不如逻辑 "and\or"运算符聪明

标签 c# optimization operators bit-manipulation

我只是注意到按位运算不如逻辑“与\或”运算那么“智能”,我想知道为什么?

这是一个例子:

// 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 & yx = 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/

相关文章:

c# - 将数据从远程服务器拉到本地服务器......最好,最安全的方式

python - 如何查找列表中的任何元素是否存在于字典中

angular - 在可观察对象上使用 first() 运算符来获取第一个元素

Java |= 运算符问题

C#:如何舍入小数并将其分配给 int16?

c# - 在没有xml文件的情况下初始化log4net

c# - 从串口获取数据失败

php - MySQL + PHP : ~500kb JSON file - Loading data as tables and fields VS as a single serialized variable

c - 矩阵旋转的性能优化

python - 尝试在 Python 中使用运算符方法时出现类型错误