AND / OR(安培;&安培; / ||)逻辑多个条件语句 [英] AND/OR (&&/||) logic for multiple condition statements
问题描述
如果你有在C#中的if语句来检查多个条件:
If you have an if-statement in C# that checks multiple conditions:
if (a == 5 && b == 9) { ... }
确实乙== 9 仍然可以检查是否 == 5 的条件是假的,或者可以自动进行退出,因为没有办法,这可能传递了?
Does b == 9 still get checked if a == 5 condition is false, or does it automatically exit since there's no way this could pass anymore?
同样,对于一个OR if语句:
Similarly, for an OR if-statement:
if (a == 5 || b == 9) { ... }
威尔的乙== 9 仍然可以检查是否 == 5 是真的
Will b == 9 still get checked if a == 5 is true?
推荐答案
两个&放大器;?&安培;
和 ||
是短路的运营商,这意味着,如果答案是从左边的操作数已知的,正确的操作数不计算。
Both &&
and ||
is "short-circuiting" operators, which means that if the answer is known from the left operand, the right operand is not evaluated.
这意味着:
a && b
B
不会,如果<评估。code> A 是假的,因为最后的答案是已知
b
will not be evaluated if a
is false, since the final answer is already known.
同样的:
a || b
B
不会,如果<评估code> A 是真实的,因为最后的答案是已知的。
b
will not be evaluated if a
is true, since the final answer is already known.
如果您的希望的两个操作数进行评估,使用&放大器;
和 |
运营商,而不是
If you want both operands to be evaluated, use the &
and |
operators instead.
这样做的好处是,你可以写,如果所有的操作数进行评估,将失败的表现。下面是一个典型的if语句:!
The bonus of this is that you can write expressions that would fail if all operands was evaluated. Here's a typical if-statement:
if (a != null && a.SomeProperty != null && a.SomeProperty.Inner != null)
... use a.SomeProperty.Inner
如果一个为null,表达式会继续评估 a.SomeProperty
,它会抛出一个的NullReferenceException
,但由于&放大器;&安培;
短路,如果 A
是空$ 。C $ C>,表达不会评价休息,因此不会抛出异常。
If a was null, and the expression would go on to evaluate a.SomeProperty
, it would throw a NullReferenceException
, but since &&
short-circuits, if a
is null
, the expression will not evaluate the rest and thus not throw the exception.
显然,如果你替换&放大器;&安培;
与&安培;
,它会抛出该异常如果 A
或 a.SomeProperty
是空
。
Obviously, if you replace &&
with &
, it will throw that exception if either a
or a.SomeProperty
is null
.
这篇关于AND / OR(安培;&安培; / ||)逻辑多个条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!