(OrElse and Or) and (AndAlso and And) - 什么时候使用? [英] (OrElse and Or) and (AndAlso and And) - When to use?

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

问题描述

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

解决方案

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

OrElse/AndAlso短路.仅当无法仅通过对左侧表达式的评估来确定结果时,才会评估右侧表达式.(这意味着:如果左表达式为假,OrElse 只会计算右表达式,如果左表达式为真,AndAlso 只会计算右表达式.)>

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

然而,在许多情况下,表达式依赖的.例如,当 List 不是 Nothing 并且有多个元素时,我们想要做一些事情:

If list IsNot Nothing AndAlso list.Length >0 然后 .. 'list 有东西

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

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

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

快乐编码.

<小时>

1 在第一个表达式中抛出的异常会阻止第二个表达式被求值,但这应该不足为奇..

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 will always evaluate both1 the expressions and then return a result. They are not short-circuiting.

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.

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

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.

Happy coding.


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

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

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