C# 中逻辑 AND、OR 和条件 AND、OR 有什么区别?
可能的重复:
| 之间有什么区别和 ||还是运算符?
逻辑AND 和OR:
(x & y)
(x | y)
条件AND 和OR:
(x && y)
(x || y)
到目前为止我只知道条件操作数。我知道它的作用以及如何在 if 语句中应用它。但是逻辑操作数的目的是什么?
Possible Duplicate:
What is the diffference between the | and || or operators?
Logical AND and OR:
(x & y)
(x | y)
Conditional AND and OR:
(x && y)
(x || y)
I've only known about conditional operands up to this point. I know what it does and how to apply it in if-statements. But what is the purpose of logical operands?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我更喜欢将其视为“按位与条件”而不是“逻辑与条件”,因为“逻辑”的一般概念适用于这两种情况。
编辑
根据大众的要求,我还应该提到,对论点的评估是不同的。在条件版本中,如果整个操作的结果可以由第一个参数确定,则不计算第二个参数。这称为短路评估。位运算必须评估两边才能计算最终值。
例如:
如果
x.foo()
计算结果为true
,则仅调用y.bar()
。相反,如果
x.foo()
计算结果为false
,则仅调用y.bar()
。I prefer to think of it as "bitwise vs. conditional" rather than "logical vs conditional" since the general concept of "logical" applies in both cases.
Edit
By popular demand, I should also mention that the arguments are evaluated differently. In the conditional version, if the result of the entire operation can be determined by the first argument, the second argument is not evaluated. This is called short-circuit evaluation. Bitwise operations have to evaluate both sides in order to compute the final value.
For example:
This will only call
y.bar()
ifx.foo()
evaluates totrue
. Conversely,will only call
y.bar()
ifx.foo()
evaluates tofalse
.很懒。如果 x 为真,它只会评估 y。
并不懒惰。 y 将始终被评估。
is lazy. It will only evaluate y if x is true.
is not lazy. y will always be evaluated.
更新答案 - 我的原始答案具有误导性且不完整。
首先,我应该为我对这个问题的大部分评论和回答道歉。
阅读规范后,按位运算符和条件运算符之间的区别就不太清楚了。
根据 ECMA-334 的14.10部分:
对于整数运算:
根据14.11:部分
14.11.1
14.11.2
Updated Answer - my original was misleading and incomplete.
First I should apologize for much of my comments and responses to this question.
After reading the spec, the distinction between bitwise and conditional operators is much less clear cut.
According to section 14.10 of ECMA-334:
for integer operations:
According to section 14.11:
14.11.1
14.11.2