转载:C#中&与&&的区别
Posted chinafine
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了转载:C#中&与&&的区别相关的知识,希望对你有一定的参考价值。
以前都没怎么注意两者的区别(我甚至都不知道“&”),因为它们都是“与”运算符。我昨天看C#高编第三版的时候,才注意到这点,查了下MSDN,把区别贴出来,时时提醒自己。
二元运算符 (&) 为整型和 bool 类型预定义了二进制 & 运算符。对于整型,& 计算操作数的按位“与”。对于 bool 操作数,& 计算操作数的逻辑“与”;也就是说,当且仅当两个操作数均为 true 时,其结果才为 true。条件“与”运算符 (&&) 执行布尔操作数的逻辑“与”运算,但如有必要,只计算第二个操作数。它与二元运算符 (&)很像,不同的是,如果 x 为 false,则不计算 y(因为不论 y 为何值,与操作的结果都为 false)。这被称作为“短路”计算。
下面的例子最能说明问题
![](https://image.cha138.com/20210612/d151cf5f40c74e3baadc8c12af69374f.jpg)
![](https://image.cha138.com/20210612/d151cf5f40c74e3baadc8c12af69374f.jpg)
![](https://image.cha138.com/20210612/d151cf5f40c74e3baadc8c12af69374f.jpg)
![](https://image.cha138.com/20210612/0fbec36419cd4128a7f70c593d995f5e.jpg)
![](https://image.cha138.com/20210612/4ff2c2e7323e4c0da82d3380ac87de9c.jpg)
![](https://image.cha138.com/20210612/86a1b365c8ca46179fb49babfbafed0c.jpg)
![](https://image.cha138.com/20210612/4ff2c2e7323e4c0da82d3380ac87de9c.jpg)
![](https://image.cha138.com/20210612/4ff2c2e7323e4c0da82d3380ac87de9c.jpg)
![](https://image.cha138.com/20210612/3f97caa7aecc4ddf8a2d37693e1cb9f2.jpg)
![](https://image.cha138.com/20210612/4ff2c2e7323e4c0da82d3380ac87de9c.jpg)
![](https://image.cha138.com/20210612/4ff2c2e7323e4c0da82d3380ac87de9c.jpg)
![](https://image.cha138.com/20210612/86a1b365c8ca46179fb49babfbafed0c.jpg)
![](https://image.cha138.com/20210612/4ff2c2e7323e4c0da82d3380ac87de9c.jpg)
![](https://image.cha138.com/20210612/4ff2c2e7323e4c0da82d3380ac87de9c.jpg)
![](https://image.cha138.com/20210612/3f97caa7aecc4ddf8a2d37693e1cb9f2.jpg)
![](https://image.cha138.com/20210612/4ff2c2e7323e4c0da82d3380ac87de9c.jpg)
![](https://image.cha138.com/20210612/4ff2c2e7323e4c0da82d3380ac87de9c.jpg)
![](https://image.cha138.com/20210612/86a1b365c8ca46179fb49babfbafed0c.jpg)
![](https://image.cha138.com/20210612/4ff2c2e7323e4c0da82d3380ac87de9c.jpg)
![](https://image.cha138.com/20210612/4ff2c2e7323e4c0da82d3380ac87de9c.jpg)
![](https://image.cha138.com/20210612/4ff2c2e7323e4c0da82d3380ac87de9c.jpg)
![](https://image.cha138.com/20210612/4ff2c2e7323e4c0da82d3380ac87de9c.jpg)
![](https://image.cha138.com/20210612/3f97caa7aecc4ddf8a2d37693e1cb9f2.jpg)
![](https://image.cha138.com/20210612/1faa8c5662d14082b4ab60a40c6a8def.jpg)
输出:
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.
(|) 与 (||) 运算符也是一样的道理
以上是关于转载:C#中&与&&的区别的主要内容,如果未能解决你的问题,请参考以下文章