正是依靠和放大器;&安培;短路安全的.NET? [英] Is relying on && short-circuiting safe in .NET?
问题描述
假设MyObj中为空。它是安全的写?
Assume myObj is null. Is it safe to write this?
if(myObj != null && myObj.SomeString != null)
我知道有些语言将不会执行第二个前pression因为和放大器;&安培;计算结果为false时执行第二部分之前。
I know some languages won't execute the second expression because the && evaluates to false before the second part is executed.
推荐答案
是的。在C#&功放;&安培;
和 ||
的短路,从而计算右侧只有左侧尚不确定结果。运营商&安培;
和 |
,另一方面没有短路和始终评估双方
Yes. In C# &&
and ||
are short-circuiting and thus evaluates the right side only if the left side doesn't already determine the result. The operators &
and |
on the other hand don't short-circuit and always evaluate both sides.
该规范说:
在&功放;&安培;
和 ||
运算符称为条件逻辑运算符。他们也被称为短路逻辑运算符。
...
操作 X - 安培;&安培;是
对应于操作 X'放大器;是
,但是
只计算,如果 X
是真正的
...
操作 X - 安培;&安培;是
被评为(布尔)×? (布尔)Y:假
。换句话说, X
第一次评估,并转换为类型布尔
。然后,如果 X
是真
,是
评估和转换为类型布尔
,并且这成为运算的结果。否则,操作的结果是假
。
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条件逻辑运算符)的
的一个有趣的性质&功放;&安培;
和 ||
的是,他们短路,即使他们不T操作的布尔变量,但类型,用户重载运算符&安培;
或 |
加上真
和假
运营商。
One interesting property of &&
and ||
is that they are short circuiting even if they don't operate on bools, but types where the user overloaded the operators &
or |
together with the true
and false
operator.
操作 X - 安培;&安培;是
被评为 T.false((T)x)的? (T)X:T。及((T)X,Y)
,其中
T.false((T)x)
是运算错误的调用
在声明牛逼
和 T。及((T)X
,y)是选择运营商和放大器的调用;
。此外,值(T)×应只计算一次。
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.
在换句话说, X
第一次评估,并转换为类型 T
和运营商假
被调用的结果,以确定是否 X
绝对假
。
然后,如果 X
肯定是假
,操作的结果是价值previously计算了 X
转换为类型 T
。
否则,是
进行评估,并选择运营商&安培;
的价值previously计算了调用 X
转换为类型 T
,并计算了 Y的值
来产生的操作的结果。
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用户定义的条件逻辑运算符)的
这篇关于正是依靠和放大器;&安培;短路安全的.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!