我正在尝试在 vb.net 中使用 IIF,这是我的代码
Dim arr as new MyClass("ABC")
MyAnotherMethod(IIf(arr.SelectedValue.Count < 1, Nothing, arr.SelectedValue(0).Value),"xxx","yyy","zzz")
上面的 IIF 将运行到 true 部分,但是在我运行此代码后,我收到以下消息:
Index was outside the bounds of the array.
我认为原因是虽然应该运行 true 部分,但 arr.SelectedValue(0).Value 已传递到 IIF,因此仍引用 false 部分。
有没有像“andalso”这样的逻辑适合我的情况?以免跑假部分。
非常感谢!
最佳答案
您需要使用 IF Operator而不是 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)
关于.net - 如何避免在 IIF 中遇到错误的部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11538811/