VB.NET带有'或'条件的'If'语句双方都经过评估了吗? [英] VB.NET 'If' statement with 'Or' conditional has both sides evaluated?

查看:41
本文介绍了VB.NET带有'或'条件的'If'语句双方都经过评估了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速问题,最快和最简单的答案可能就是重新排列相关代码,但是让我们看看...

Quick question, of which the quickest and easiest answer may well be to rearrange related code, but let's see...

所以我有一个 If 语句(一段代码,它是用C#编写的完整工作解决方案的一部分),是使用VB.NET重写的.我知道VB.NET IIf(a,b,c)方法会同时评估 b a ,而不管第一次评估的真实性如何,但在我的标准构造中,似乎也是如此:

So I have an If statement (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 b and a regardless of the trueness of the first evaluation, but this seems to be the case in my standard construct, too:

If (example Is Nothing Or example.Item IsNot compare.Item) Then
    'Proceed
End If

或者,更恰当地说:

If (example Is Nothing Or Not example.Item = compare.Item) Then
    'Proceed
End If

在这里,如果 example Nothing ( null ),那么我仍然会收到 NullReferenceException -这是我的吗?是错误的,还是我只需要忍受VB.NET的一时冲动?

Here, if example is 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?

推荐答案

这是您的错误",这就是 Or 已定义,因此这是您应该期望的行为:

It's your "fault" in that that's how Or is defined, so it's the behaviour you should expect:

在布尔比较中,或"运算符始终对两个表达式求值,这可能包括进行过程调用.OrElse运算符(Visual Basic)执行短路,这意味着如果expression1为True,则不对expression2求值.

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.

但是您不必忍受它.您可以使用 OrElse 来获得-循环行为.

But you don't have to endure it. You can use OrElse to get short-circuiting behaviour.

所以您可能想要:

If (example Is Nothing OrElse Not example.Item = compare.Item) Then
    'Proceed
End If

我不能说它读得很好,但是它应该可以工作...

I can't say it reads terribly nicely, but it should work...

这篇关于VB.NET带有'或'条件的'If'语句双方都经过评估了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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