(OrElse和Or)和(AndAlso和And)-何时使用? [英] (OrElse and Or) and (AndAlso and And) - When to use?

查看:63
本文介绍了(OrElse和Or)和(AndAlso和And)-何时使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(OrElse和Or)与(AndAlso和And)之间有什么区别? 他们的表现有什么不同,可以说正确性好处吗?有什么我不应该使用OrElse和AndAlso的情况吗?

What is the difference between (OrElse and Or) and (AndAlso and And)? Is there any difference in their performances, let say the correctness benefit?? Is there any situation that I shoudn't use OrElse and AndAlso?

推荐答案

Or/And总是 评估两者 1 表达式,然后返回结果.它们不是短路.

Or/And will always evaluate both1 the expressions and then return a result. They are not short-circuiting.

OrElse/AndAlso短路.仅当无法仅通过对左表达式的评估无法确定结果时,才对右表达式进行评估. (这意味着:OrElse仅在左表达式为假的情况下评估右表达式,而AndAlso仅在左表达式为真的情况下评估右表达式.)

OrElse/AndAlso are short-circuiting. The right expression is only evaluated if the outcome cannot be determined from the evaluation of the left expression alone. (That means: OrElse will only evaluate the right expression if the left expression is false, and AndAlso will only evaluate the right expression if the left expression is true.)

假设表达式中没有副作用 并且表达式不相关(并且忽略了任何执行开销),则它们是相同的.

Assuming that no side effects occur in the expressions and the expressions are not dependent (and any execution overhead is ignored), then they are the same.

但是,在很多情况下,表达式依赖的.例如,当列表不是-Nothing并且具有多个元素时,我们想做一些事情:

However, in many cases it is that the expressions are dependent. For instance, we want to do something when a List is not-Nothing and has more than one element:

If list IsNot Nothing AndAlso list.Length > 0 Then .. 'list has stuff

这也可以用来避免昂贵的"计算(或副作用,!​​):

This can also be used to avoid an "expensive" computation (or side-effects, ick!):

If Not Validate(x) OrElse Not ExpensiveValidate(x) Then .. 'not valid

就我个人而言,我发现AndAlsoOrElse正确运算符,希望在除1%或更少的比例之外的所有比例中使用! -需要副作用 的情况.

Personally, I find that AndAlso and OrElse are the correct operators to use in all but the 1% - or less, hopefully! - of the cases where a side-effect is desired.

快乐的编码.

1 在第一个表达式中引发异常将阻止对第二个表达式进行求值,但这并不令人惊讶..

1 An Exception thrown in the first expression will prevent the second expression from being evaluated, but this should hardly be surprising ..

这篇关于(OrElse和Or)和(AndAlso和And)-何时使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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