gpt4 book ai didi

vb.net - IIF 行为不正确

转载 作者:行者123 更新时间:2023-12-01 22:38:57 25 4
gpt4 key购买 nike

我想知道为什么以下行行为不正确。当我使用 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() 版本,即使 bool 值计算结果为 true,也会调用 GetMessage(),这可能会导致副作用。使用 If() 时,仅计算正确的返回值:

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

编辑:添加示例代码,以更清楚地了解 If() 与 IIF(),并使用 dotnetfiddle 示例 fiddle :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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com