假设 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 operationx && y
corresponds to the operationx & y
, except thaty
is evaluated only ifx
istrue
...
The operationx && y
is evaluated as(bool)x ? (bool)y : false
. In other words,x
is first evaluated and converted to typebool
. Then, ifx
istrue
,y
is evaluated and converted to typebool
, and this becomes the result of the operation. Otherwise, the result of the operation isfalse
.
(C# 语言规范版本 4.0 - 7.12 条件逻辑运算符)
&&
和 ||
的一个有趣的属性是它们短路,即使它们不对 bool 操作,但是用户重载操作符的类型 &
或 |
以及 true
和 false
运算符。
The operation
x && y
is evaluated asT.false((T)x) ? (T)x : T.&((T)x, y)
, whereT.false((T)x)
is an invocation of theoperator false
declared inT
, andT.&((T)x
, y) is an invocation of the selectedoperator &
. In addition, the value (T)x shall only be evaluated once.In other words,
x
is first evaluated and converted to typeT
andoperator false
is invoked on the result to determine ifx
is definitelyfalse
.
Then, ifx
is definitelyfalse
, the result of the operation is the value previously computed forx
converted to typeT
.
Otherwise,y
is evaluated, and the selected operator&
is invoked on the value previously computed forx
converted to typeT
and the value computed fory
to produce the result of the operation.
(C# 语言规范版本 4.0 - 7.12.2 用户定义的条件逻辑运算符)
关于c# - 在 .NET 中依赖 && 短路安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4820610/