在任何编程语言中,使用Null时都要小心。上面的示例显示了另一个问题。如果使用Nullable类型,则意味着从该类型实例化的变量可以包含值System.DBNull.Value;。不是因为它已更改了使用“ = Nothing”将值设置为默认值的解释,也不是值的对象现在可以支持空引用。只是警告...编码愉快!
您可以创建一个包含值类型的单独的类。从此类创建的对象将是引用类型,可以将其分配为Nothing。一个例子:
Public Class DateTimeNullable
Private _value As DateTime
Public Property Value() As DateTime
Get
Return _value
End Get
Set(ByVal value As DateTime)
_value = value
End Set
End Property
Public Sub New()
Value = DateTime.MinValue
End Sub
Public Sub New(ByVal dt As DateTime)
Value = dt
End Sub
Public Overrides Function ToString() As String
Return Value.ToString()
End Function
末级
'在Main()中:
Dim dtn As DateTimeNullable = Nothing
Dim strTest1 As String = "Falied"
Dim strTest2 As String = "Failed"
If dtn Is Nothing Then strTest1 = "Succeeded"
dtn = New DateTimeNullable(DateTime.Now)
If dtn Is Nothing Then strTest2 = "Succeeded"
Console.WriteLine("test1: " & strTest1)
Console.WriteLine("test2: " & strTest2)
Console.WriteLine(".ToString() = " & dtn.ToString())
Console.WriteLine(".Value.ToString() = " & dtn.Value.ToString())
Console.ReadKey()
然后,您可以选择可覆盖对象以使其满足您的需要。大量的工作-但如果您确实需要它,可以做到。