c# - 在 .NET 中依赖 && 短路安全吗?

标签 c# .net operators logical-operators short-circuiting

假设 myObj 为空。这样写安全吗?

if(myObj != null && myObj.SomeString != null)

我知道有些语言不会执行第二个表达式,因为在执行第二部分之前 && 的计算结果为 false。

最佳答案

是的。在 C# 中,&&|| 是短路的,因此仅当左侧尚未确定结果时才评估右侧。另一方面,运算符 &| 不会短路,并且始终对两侧求值。

规范说:

The && and || operators are called the conditional logical operators. They are also called the “shortcircuiting” logical operators.
...
The operation x && y corresponds to the operation x & y, except that y is evaluated only if x is true
...
The operation x && y is evaluated as (bool)x ? (bool)y : false. In other words, x is first evaluated and converted to type bool. Then, if x is true, y is evaluated and converted to type bool, and this becomes the result of the operation. Otherwise, the result of the operation is false.

(C# 语言规范版本 4.0 - 7.12 条件逻辑运算符)

&&|| 的一个有趣的属性是它们短路,即使它们不对 bool 操作,但是用户重载操作符的类型 &| 以及 truefalse 运算符。

The operation x && y is evaluated as T.false((T)x) ? (T)x : T.&((T)x, y), where T.false((T)x) is an invocation of the operator false declared in T, and T.&((T)x, y) is an invocation of the selected operator &. In addition, the value (T)x shall only be evaluated once.

In other words, x is first evaluated and converted to type T and operator false is invoked on the result to determine if x is definitely false.
Then, if x is definitely false, the result of the operation is the value previously computed for x converted to type T.
Otherwise, y is evaluated, and the selected operator & is invoked on the value previously computed for x converted to type T and the value computed for y to produce the result of the operation.

(C# 语言规范版本 4.0 - 7.12.2 用户定义的条件逻辑运算符)

关于c# - 在 .NET 中依赖 && 短路安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4820610/

相关文章:

c# - 如何在 EF4 中指定与实体不同的表名?

javascript - JavaScript 中所有二元运算符的列表

c# - 在处理不可为空类型的空值的 setter 上停止 C# 警告 "Possible Null Reference Assignment"

c# - Entity Framework 4 中的 Linq 查询。糟糕的性能

c# - 进行 Http 调用时套接字异常

c++ - QTCreator 中的运算符>>不匹配

Perl:代码差异

c# - C#中使用长保留字作为变量名

c# - 在用户的默认浏览器中打开网站而不让他们启动其他任何东西?

c# - 通过带有自签名 SSL 证书的邮件服务器从 .net 应用程序发送电子邮件