如何避免在IIF中遇到错误的部分?

Ste*_*Lam 4 .net vb.net iif

我想在vb.net中使用IIF,这是我的代码

Dim arr as new MyClass("ABC")
MyAnotherMethod(IIf(arr.SelectedValue.Count < 1, Nothing, arr.SelectedValue(0).Value),"xxx","yyy","zzz")
Run Code Online (Sandbox Code Playgroud)

上面的IIF会遇到真正的部分,但是在我运行这段代码之后,我得到了以下消息:

指数数组的边界之外.

我认为原因是虽然应该运行true part,但arr.SelectedValue(0).Value已经传入IIF,因此仍然会引用false部分.

有什么逻辑像"andalso",适合我的情况?为了避免运行虚假部分.

非常感谢!

Mat*_*lko 7

您需要使用IF运算符而不是IIF函数

"使用三个参数调用的If运算符与IIf函数类似,只是它使用短路评估"

它也是类型安全的,而IIF并非如此,你应该真正使用它.看看这些有用的例子:

    Dim i As Integer

    'compiles if option strict is off (this is bad)
    i = IIf(True, "foo", 4) 

    'compiles even if option strict on, but results in a runtime error (this is even worse)
    i = CInt(IIf(True, "foo", 4)) 

    'won't compile (this is good because the compiler spotted the mistake for you)
    i = If(True, "foo", 4) 
Run Code Online (Sandbox Code Playgroud)