AND/OR (amp;amp;/||) logic for multiple condition statements(多个条件语句的 AND/OR (amp;amp;/||) 逻辑)
问题描述
如果您在 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,但由于 && 短路,如果 a 为 null,则表达式不会计算其余部分,因此不会抛出异常.
显然,如果您将 && 替换为 &,如果 a 或 a.SomeProperty 为 null.
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 (&&/||) 逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:多个条件语句的 AND/OR (&&/||) 逻辑
基础教程推荐
- 如果条件可以为空 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 将数据集转换为列表 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
