IIF没有正确行为

时间:2015-01-20 02:51:17

标签: vb.net iif

我想知道为什么以下行行为不正确。当我使用IIF时,虽然当条件为True时,该函数返回getMessage

Return CType(IIf(Object.Equals(_newValue, _oldValue), 
             msg, GetMessage(msg)), PooMessage)

但以下几行表现得很好:

If Object.Equals(_newValue, _oldValue) Then
        Return msg
Else
        Return CType(GetMessage(msg), PooMessage)
End If

2 个答案:

答案 0 :(得分:2)

您应该从IIf()更改为If(),因为后者使用短路而前者不使用短路。使用IIf()版本,即使布尔值计算为true,也会调用GetMessage(),这可能会导致副作用。使用If()时,仅评估正确的返回值:

Return CType(If(Object.Equals(_newValue, _oldValue), msg, GetMessage(msg)), PooMessage)

编辑:添加示例代码以更清晰地了解If()与IIF(),使用dotnetfiddle示例 小提琴:https://dotnetfiddle.net/vuMPgK

代码:

Imports System
Imports Microsoft.VisualBasic

Public Module Module1
    Public Sub Main()

        Dim didItWork as Boolean = False
        Dim myTestObject as Test = Nothing

        ' works, due to IF(). Only the 'true' value is calculated
        didItWork = If(myTestObject Is Nothing, False, myTestObject.MyValue)

            Console.WriteLine("Did If() work?: " & didItWork.ToString())


            ' does not work, due to IIF().  Both True and False conditions are calculated regardless of the original test condition.
            '  it fails because myTestObject is null, so trying to access one of its properties causes an exception.
            Try
                didItWork = IIF(myTestObject Is Nothing, False, myTestObject.MyValue)
                Console.WriteLine("Did IIF() work?: " & didItWork.ToString())
            Catch ex as Exception
                Console.WriteLIne("Error was thrown from IIF")
            End Try

    End Sub
End Module

Public Class Test
        Public Property MyValue as Boolean = True
End class

答案 1 :(得分:2)

要理解@Idle_Mind,原因如下......

r=IIF(x,y,z) 

函数调用。为了调用它,所有参数(x,y和z)必须在进入函数体之前进行评估。

r=IF(x,y,z) 

编译器指令。代码中创建" y"和" z" 看起来像函数调用的部分直到在" x"上进行比较后才会被评估。如果有效编译为完整的IF ELSE END IF结构,如下所示......

if x then
    r=y
else
    r=z
end if

值得注意的一点是,无论何时你在VB.Net中看到的文字都是" Ctype"是彩色的,它是编译器指令而不是传统的代码单元。