简体   繁体   English

vb.net - IIf抛出奇怪的异常

[英]vb.net - IIf throwing strange exception

I am having a weird problem. 我有一个奇怪的问题。 IIf is messing up when I am working with an array. 当我使用数组时,IIf正在搞乱。 Apparently it is checking my else statement even though it isn't activated. 显然它正在检查我的其他声明,即使它没有被激活。 Here is some code that demonstrates the issue: 以下是一些演示此问题的代码:

'works
 Dim test As String = "bleh"
 If values.Length < 6 Then
   test = "200"
 Else
   test = values(5)
 End If

 'throws indexoutofrange exception
 Dim itemLimit As String = IIf(values.Length < 6, "200", values(5))

The Iif operator doesn't implement short circuiting and will evaluate both the true and false case. Iif运算符不实现短路,并将评估真假情况。 If you want a short-circuit version then use If . 如果你想要一个短路版本,那么使用If

Dim itemLimit As String = If(values.Length < 6, "200", values(5))

Have a look at this article: http://www.fmsinc.com/free/newtips/net/nettip33.asp 看看这篇文章: http//www.fmsinc.com/free/newtips/net/nettip33.asp

From the article: 来自文章:

Visual Basic, VBA, and Visual Basic .NET support the IIF function as an alternative to the If...Then...Else statement. Visual Basic,VBA和Visual Basic .NET支持IIF函数作为If ... Then ... Else语句的替代。 Although this may seem like a shortcut, IIF functions differently than If...Then...Else. 虽然这似乎是一种捷径,但IIF的功能与If ... Then ... Else不同。

IIF must evaluate the entire statement when preparing the argument, which can lead to undesirable side effects. IIF必须在准备论证时评估整个陈述,这可能导致不良副作用。

In other words, your If...Then...Else works because the Else clause isn't being evaluated if the condition fails. 换句话说,你的If...Then...Else有效的,因为如果条件失败,则不会评估Else子句。 The IIf , on the other hand, evaluates all the statements, causing the IndexOutOfBounds exception. 另一方面, IIf评估所有语句,从而导致IndexOutOfBounds异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM