无法将字符串变量的默认值设置为DBNull

时间:2019-10-24 16:02:08

标签: .net vb.net

我的理解是VB.NET中的数据类型String可为空。

因此,我不明白为什么以下代码返回错误“无法将DBNull的值转换为字符串”

Public name As String = DBNull.Value

对于上下文,我有一个其值将被写入数据库的类。创建类的对象时,可能并非其所有变量都具有值。我希望数据库中的缺失值是null,因此我打算如上所述将变量的默认值设置为DBNull。但这由于上述错误而无法正常工作。

3 个答案:

答案 0 :(得分:2)

DBNull并不真正等同于Nothing。这是一堂课。 Valueshared对象的DBNull字段,它仅将Value的值设置为DBNull类的实例。您可以自己here看到它。

答案 1 :(得分:0)

DBNull无法转换为字符串,您需要对其进行测试。您可以将Nothing分配给字符串,因此可以使用:

    Public name As String = Nothing

答案 2 :(得分:0)

要对数据库执行写操作,可以使用Nothing作为值,然后在写数据库时检查yourString Is Nothing,如果是,则设置参数的值到DBNull.Value

Public Class Datum
    Property Name As String = Nothing
End Class

Sub X()
    Dim q As New Datum

    Using cmd As New SqlCommand()
        ' other code...

        cmd.Parameters.Add(New SqlParameter With {.ParameterName = "@Name", .SqlDbType = SqlDbType.NVarChar, .Size = 123})
        If q.Name Is Nothing Then
            cmd.Parameters("@Name").Value = DBNull.Value
        Else
            cmd.Parameters("@Name").Value = q.Name
        End If

        ' other code....
    End Using

End Sub

为了正确操作,请在检查Is时使用IsNotNothing运算符,不要使用=运算符。

相关问题