문제

나는 이상한 문제가있다.배열로 작업 할 때 IIF가 엉망이됩니다.분명히 활성화되지 않더라도 다른 진술을 확인하고 있습니다.다음은 문제를 보여주는 몇 가지 코드입니다.

'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. If you want a short-circuit version then use 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

From the article:

Visual Basic, VBA, and Visual Basic .NET support the IIF function as an alternative to the If...Then...Else statement. Although this may seem like a shortcut, IIF functions differently than If...Then...Else.

IIF must evaluate the entire statement when preparing the argument, which can lead to undesirable side effects.

In other words, your If...Then...Else works because the Else clause isn't being evaluated if the condition fails. The IIf, on the other hand, evaluates all the statements, causing the IndexOutOfBounds exception.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top