在任何编程语言中,使用 Null 时都要小心。上面的示例显示了另一个问题。如果使用 Nullable 类型,则意味着从该类型实例化的变量可以保存值 System.DBNull.Value;并不是说它改变了使用“= Nothing”将值设置为默认值的解释,或者值的对象现在可以支持空引用。只是一个警告......快乐的编码!
您可以创建一个包含值类型的单独类。从这样的类创建的对象将是一个引用类型,它可以被赋值为 Nothing。一个例子:
Public Class DateTimeNullable
Private _value As DateTime
'properties
Public Property Value() As DateTime
Get
Return _value
End Get
Set(ByVal value As DateTime)
_value = value
End Set
End Property
'constructors
Public Sub New()
Value = DateTime.MinValue
End Sub
Public Sub New(ByVal dt As DateTime)
Value = dt
End Sub
'overridables
Public Overrides Function ToString() As String
Return Value.ToString()
End Function
结束类
'在主():
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()
' Output:
'test1: Succeeded()
'test2: Failed()
'.ToString() = 4/10/2012 11:28:10 AM
'.Value.ToString() = 4/10/2012 11:28:10 AM
然后,您可以挑选并选择可覆盖的内容以使其满足您的需求。很多工作 - 但如果你真的需要它,你可以做到。