多个条件语句的 AND/OR (&&/||) 逻辑 [英] AND/OR (&&/||) logic for multiple condition statements

查看:48
本文介绍了多个条件语句的 AND/OR (&&/||) 逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您在 C# 中有一个检查多个条件的 if 语句:

if (a == 5 && b == 9) { ... }

如果 a == 5 条件为假,是否仍会检查 b == 9,还是会自动退出,因为这无法通过了?p>

同样,对于 OR if 语句:

if (a == 5 || b == 9) { ... }

如果 a == 5 为真,是否仍会检查 b == 9?

解决方案

&&|| 都是短路"运算符,这意味着如果从左操作数知道答案,则不计算右操作数.

这意味着:

一个 &&b

如果 a 为假,则不会评估

b,因为最终答案是已知的.

同样:

a ||b

如果 a 为真,则不会评估

b,因为最终答案是已知的.

如果您想要对两个操作数都进行求值,请改用 &| 运算符.

这样做的好处是您可以编写如果所有操作数都被求值就会失败的表达式.这是一个典型的 if 语句:

if (a != null && a.SomeProperty != null && a.SomeProperty.Inner != null)...使用 a.SomeProperty.Inner

如果 a 为 null,并且表达式将继续计算 a.SomeProperty,它将抛出 NullReferenceException,但由于 && 短路,如果 anull,则表达式不会计算其余部分,因此不会抛出异常.

显然,如果您将 && 替换为 &,如果 aa.SomePropertynull.

If you have an if-statement in C# that checks multiple conditions:

if (a == 5 && b == 9) { ... }

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?

Similarly, for an OR if-statement:

if (a == 5 || b == 9) { ... }

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.

This means that:

a && b

b will not be evaluated if a is false, since the final answer is already known.

Likewise:

a || b

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.

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

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.

Obviously, if you replace && with &, it will throw that exception if either a or a.SomeProperty is null.

这篇关于多个条件语句的 AND/OR (&&/||) 逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆