是否在三元运算符中评估了两条路径?

时间:2013-09-05 13:44:33

标签: vb.net

使用vb.net,以下代码抛出空指针异常,但表达式应保证match不为空。

repeater.DataSource = IIf(collection IsNot Nothing AndAlso match IsNot Nothing, collection.FindAll(match), collection)

使用常规的if-else构造替换它不会引发错误:

If collection IsNot Nothing AndAlso match IsNot Nothing Then
    repeater.DataSource = collection.FindAll(match)
Else
    repeater.DataSource = collection
End If

是否在三元运算符中评估了两个路径?

2 个答案:

答案 0 :(得分:3)

If Operator (Visual Basic) - MSDN

  

使用三个参数调用的If运算符类似于IIf   功能除了它使用短路评估。一个 IIf   函数总是评估它的所有三个参数

答案 1 :(得分:1)

是的,双方都要进行评估,您应该避免使用IIf()语法,而是使用If(),因为If()会与AndAlso短路。

有关详细信息,请阅读VB.NET - IIF(,,) - Both “sides” are evaluated. What situations should I watch out for?的接受答案。

相关问题