在我的ASP.Net Web应用程序中,出现此错误:
Conversion from type 'DBNull' to type 'Boolean' is not valid.
通过此功能:
Namespace atc
Public Class Nil
'...
Public Shared Function Bool(ByVal Item As Object) As Boolean
Return IIf(Item IsNot Nothing AndAlso Not IsDBNull(Item), CBool(Item), False)
End Function
'...
End Class
End Namespace
如您所见,我正在显式检查
Item
是否为DBNull
,如果是,则返回False
。当
Item
是而不是 DBNull
时,会发生错误而不是,所以我不明白为什么会这样。
最佳答案
当使用IIf
时,无论条件评估为true还是false,所有参数都将被求值。在您的情况下,如果Item为null或DBNull,该函数将返回false
,但是CBool(Item)
无论如何都会在后台静默执行,因此会引发异常。
在VB.NET 2008中,添加了If
关键字以提供真正的三元运算符。将您的IIf
函数调用替换为以下内容:
Public Shared Function Bool(ByVal Item As Object) As Boolean
Return If(Item IsNot Nothing AndAlso Not IsDBNull(Item), CBool(Item), False)
End Function
摘自MSDN:
An
IIf
function always evaluates all three of its arguments, whereas anIf
operator that has three arguments evaluates only two of them.
关于vb.net - “Conversion from type ' DBNull ' to type ' bool ' is not valid”,在检查它不是DBNull之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8913447/