短路声明评价 - 这是保证? [C#] [英] Short circuiting statement evaluation -- is this guaranteed? [C#]

查看:177
本文介绍了短路声明评价 - 这是保证? [C#]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速的问题在这里关于C#短路声明。与if语句是这样的:

Quick question here about short-circuiting statements in C#. With an if statement like this:

if (MyObject.MyArray.Count == 0 || MyObject.MyArray[0].SomeValue == 0)
{

//....
}

它是保证了MyArray.Count部分后评估将停止,但部分是真的吗?否则,我会在第二部分空例外。

Is it guaranteed that evaluation will stop after the "MyArray.Count" portion, provided that portion is true? Otherwise I'll get a null exception in the second part.

推荐答案

是的,这是保证。

C#语言规范 - 7.11条件逻辑运算符的:

&放大器;&安培; || 符被称为条件逻辑运算符。 他们也被称为短路逻辑运算符。

The && and || operators are called the conditional logical operators. They are also called the "short-circuiting" logical operators.

因此,他们将支持逻辑短路的定义的 - 你可以依靠这种行为

Therefore they will support logical short-circuiting by definition - you can rely on this behavior.

现在它来制作之间的区别是很重要的条件的运算符和的逻辑的运营商:

Now it is important to make a distinction between a conditional operator and a logical operator:


  • 只有有条件的运营商支持短路,逻辑运算符不

  • C#的逻辑运算符看起来就像他们的条件同行,但少了一个字符,这样一个逻辑或为 | 和一个逻辑AND是&安培;

  • 逻辑运算符可以被重载,但是有条件的经营者不能(这是一个有点技术性作为。有条件的经营者的评价确实涉及重载决议,这重载解析可以解析到该类型的逻辑运算符的自定义过载,这样你就可以解决此限制在一定程度上)。

  • Only conditional operators support short-circuiting, logical operators do not.
  • C#'s logical operators look just like their conditional counterparts but with one less character so a logical OR is | and a logical AND is &.
  • Logical operators can be overloaded but conditional operators cannot (this is a bit of an technicality as conditional operator evaluation does involve overload resolution and this overload resolution can resolve to a custom overload of the type's logical operator, so you can work around this limitation to a certain extent).

这篇关于短路声明评价 - 这是保证? [C#]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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