vb.net - “Conversion from type ' DBNull ' to type ' bool ' is not valid”,在检查它不是DBNull之后

标签 vb.net ternary-operator iif-function

在我的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 an If 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/

相关文章:

SqlDataReader vb.net 保持连接打开

reporting-services - iif函数会同时计算SSRS中的两条路径还是短路?

reporting-services - SSRS 将 NaN 更改为 0 的公式或表达式

wpf - 将转换后的 Enum 绑定(bind)到 ComboBox

c# - 在 EF 中使用单个或多个 DbContext 的优缺点是什么?

java - Java 中的三元表达式是如何求值的?

c - 使用三元运算符作为占位符

c++ - 三元表达式 which "does nothing"(noop) 如果条件为假?

function - SSRS Avg 函数返回的结果与预期不同

.net - 如何抑制 VB.NET 派生类中基类的属性或方法?