正是依靠和放大器;&安培;短路安全的.NET? [英] Is relying on && short-circuiting safe in .NET?

查看:148
本文介绍了正是依靠和放大器;&安培;短路安全的.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 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条件逻辑运算符)

的一个有趣的性质&功放;&安培; || 的是,他们短路,即使他们不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 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.

在换句话说, 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆