从左到右表达式求值 [英] Left to right expression evaluation

查看:280
本文介绍了从左到右表达式求值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#是它保证表达式求值从左向右?

In C# is it guaranteed that expressions are evaluated left to right?

例如:

myClass = GetClass();  
if (myClass == null || myClass.Property > 0)  
    continue;



是否有不符合任何语言?

Are there any languages that do not comply?

推荐答案

您实际上是指称为语言特性短路逻辑表达式:

You actually refer to a language feature called "short-circuiting logical expressions":

这句话的意思是这样的:当一个逻辑表达式的结果无法更改,如:当它是明确表示,表达式会真或假不管是什么,表达的其余部分将不进行评估。

What this means is this: When the outcome of a logical expression cannot change anymore, e.g. when it is clear that the expression will evaluate to "true" or "false" no matter what, remaining parts of the expression will not be evaluated.

例如,C#,Java或JavaScript的做到这一点,你可以在这些语言依靠它(回答你的问题)。

For example, C#, Java or JavaScript do that, and you can rely on it in those languages (to answer your question).

在你的情况,如果MyClass的不为空:

In your case, if MyClass is not null:


  • MyClass的== NULL 的值为false

  • 因为它是一个或表达,第二部分仍然可以改变的结果,因此它被评为

  • myClass.Property> 0 确定最终结果

  • MyClass == null evaluates to false
  • since it is an "or" expression, the second part still can change the result, so it is evaluated
  • myClass.Property > 0 determines the end result

如果MyClass的是空:

if MyClass is null:


  • MyClass的== NULL 的值为true

  • 因为它是一个或表达式,它无关紧要接下来

  • 没有更多的评价完成后,最终的结果是真正

  • MyClass == null evaluates to true
  • since it is an "or" expression, it does not matter what follows
  • no more evaluation is done, the end result is true

有不这样做短路逻辑表达式语言。经典VB就是一个例子,这里的myClass.Property> 0会被评估,如果产生MyClass的是空的错误(称为VB无)。

There are languages that do not short-circuit logical expressions. Classical VB is an example, here "myClass.Property > 0" would be evaluated and produce an error if MyClass was null (called "Nothing" in VB).

这篇关于从左到右表达式求值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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