以前都没怎么注意两者的区别(我甚至都不知道“&”),因为它们都是“与”运算符。我昨天看C#高编第三版的时候,才注意到这点,查了下MSDN,把区别贴出来,时时提醒自己。
二元运算符 (&) 为整型和 bool 类型预定义了二进制 & 运算符。对于整型,& 计算操作数的按位“与”。对于 bool 操作数,& 计算操作数的逻辑“与”;也就是说,当且仅当两个操作数均为 true 时,其结果才为 true。条件“与”运算符 (&&) 执行布尔操作数的逻辑“与”运算,但如有必要,只计算第二个操作数。它与二元运算符 (&)很像,不同的是,如果 x 为 false,则不计算 y(因为不论 y 为何值,与操作的结果都为 false)。这被称作为“短路”计算。
下面的例子最能说明问题
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
输出:
regular AND:
fn1 called
fn2 called
result is False
short-circuit AND:
fn1 called
result is False
fn1 called
fn2 called
result is False
short-circuit AND:
fn1 called
result is False
BTW
(&) 也可作为一元运算符,返回操作数的地址
PS.
(|) 与 (||) 运算符也是一样的道理