gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:50:24 25 4
gpt4 key购买 nike

假设 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com