我的理解是VB.NET中的数据类型String
可为空。
因此,我不明白为什么以下代码返回错误“无法将DBNull的值转换为字符串”
Public name As String = DBNull.Value
对于上下文,我有一个其值将被写入数据库的类。创建类的对象时,可能并非其所有变量都具有值。我希望数据库中的缺失值是null
,因此我打算如上所述将变量的默认值设置为DBNull。但这由于上述错误而无法正常工作。
答案 0 :(得分:2)
DBNull
并不真正等同于Nothing
。这是一堂课。 Value
是shared
对象的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
时使用IsNot
和Nothing
运算符,不要使用=
运算符。