短路:OrElse 与 Or 组合
如果我有以下内容......
a OrElse b
并且 a 是True,那么显然 b 永远不会被评估。但如果我添加一个Or
,那又怎样呢?
a OrElse b Or c
c 是否/应该被评估?如果我放入一些括号怎么办?
抱歉,如果这是基本的。当然,我可以自己测试答案,但我无法在这里或其他地方找到这个问题的答案。很多问题涉及Or与 OrElse,但没有涉及Or与 OrElse
If I have the following ...
a OrElse b
... and a is True then clearly b is never evaluated. But if I add an Or
, then what?
a OrElse b Or c
Does/should c get evaluated? And what if I put in some brackets?
Apologies if this is basic. Of course I can test for the answer myself but I can't find this question answered here or elsewhere. Lots of questions dealing with Or versus OrElse but nothing dealing with Or with OrElse
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
否则左右侧参数短路(只有2个参数)。所以我想说
C
将始终被评估,因为您可以将其视为(A OrElse B) Or C
。MSDN OrElse
OrElse short circuits between the left and right side parameters (only 2 parameters). So I would say that
C
will always be evaluated as you could treat this as(A OrElse B) Or C
.MSDN OrElse
这是一个运算符优先级问题。相关文档在这里:
http://msdn.microsoft.com/en-us/ library/fw84t893.aspx?ppud=4
重要摘录:
和
因此,我们在这里了解到 Or 和 OrElse 具有相同的优先级,并且具有相同优先级的运算符从左到右进行计算。
因此,我希望在
a
为 true 的情况下,不会评估b
。然而,c
仍然会是。如果a
为 false,则计算b
,并且无论b
的值如何,Or 运算符都会计算c.所以,是的,
c
总是被评估。实际上,您通常应该在代码中更喜欢使用
OrElse
,除非您有充分的理由使用Or
。Or
现在的存在主要是为了向后兼容。This is an operator precedence problem. The relevant documentation is here:
http://msdn.microsoft.com/en-us/library/fw84t893.aspx?ppud=4
The important excerpts:
and
So what we learn here is that Or and OrElse have the same precedence and that operators with the same precedence are evaluated from left to right.
Therefore, I would expect that in cases where
a
is true,b
is not evaluated. However,c
still will be. In cases wherea
is false,b
is evaluated and regardless of theb
's value the Or operator will evaluatec
. So, yes,c
is always evaluated.As a practical matter, you should generally prefer
OrElse
in your code unless you have a good reason to useOr
.Or
exists now mainly for backwards compatibility.在所呈现的情况下,将评估
c
。一个小测试会告诉你:上面的例子输出:
In the case presented,
c
is evaluated. A small test will tell you:The above example outputs:
根据我个人的经验,VB 倾向于获取所有这些值,无论它们是否被实际评估。
仅当订单对于项目存在等很重要时,这才有用。只是想注意一下。
In my personal experience VB tends to obtain the value for all of them regardless of whether they be actually evaulated or not.
This is only helpfull when order matters for items existance and the like. Just wanted to note it.