带有“或”条件的 VB.NET 'If' 语句是否对双方进行了评估?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4723249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.NET 'If' statement with 'Or' conditional has both sides evaluated?
提问by Grant Thomas
Quick question, of which the quickest and easiest answer may well be to rearrange related code, but let's see...
快速问题,其中最快和最简单的答案很可能是重新排列相关代码,但让我们看看......
So I have an Ifstatement (a piece of code which is a part of a full working solution written in C#) rewritten using VB.NET. I am aware the VB.NET IIf(a, b, c)method evaluates both band aregardless of the trueness of the first evaluation, but this seemsto be the case in my standard construct, too:
所以我有一个If使用 VB.NET 重写的语句(一段代码,它是用 C# 编写的完整工作解决方案的一部分)。我知道了VB.NETIIf(a, b, c)方法都进行评估b和a考虑第一评价的真实性,但这似乎是在我的标准结构的情况下,太:
If (example Is Nothing Or example.Item IsNot compare.Item) Then
'Proceed
End If
Or, rather, more appropriately:
或者,更恰当地说:
If (example Is Nothing Or Not example.Item = compare.Item) Then
'Proceed
End If
Here, if exampleis Nothing(null) then I still get an NullReferenceException- is this my fault, or is it something I just have to endure at the whim of VB.NET?
在这里,如果example是Nothing( null) 那么我仍然会得到一个NullReferenceException- 这是我的错,还是我必须在 VB.NET 的心血来潮中忍受?
回答by Jon Skeet
It's your "fault" in that that's how Oris defined, so it's the behaviour you should expect:
这是你的“错”,因为它是如何Or定义的,所以这是你应该期待的行为:
In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. The OrElse Operator (Visual Basic) performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.
在布尔比较中,Or 运算符始终计算两个表达式,其中可能包括进行过程调用。OrElse 运算符 (Visual Basic) 执行短路,这意味着如果 expression1 为 True,则不计算 expression2。
But you don't have to endure it. You can use OrElseto get short-circuiting behaviour.
但你不必忍受它。您可以使用OrElse来获得短路行为。
So you probably want:
所以你可能想要:
If (example Is Nothing OrElse Not example.Item = compare.Item) Then
'Proceed
End If
I can't say it readsterribly nicely, but it should work...
我不能说它读起来非常好,但它应该可以工作......

