我想知道为什么以下行的行为不正确。当我使用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

最佳答案

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

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


编辑:添加了示例代码,以使用dotnetfiddle示例更好地了解If()与IIF()的关系
小提琴: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

关于vb.net - IIF行为不正确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28036994/

10-12 00:24