在任何编程语言,使用空值时要小心。上面的例子显示了另一个问题。如果使用Nullable类型,则表示从该类型实例化的变量可以保存值System.DBNull。值;而不是它改变了使用“= 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
然后,你可以挑选overridables让它做你的需要。很多工作 - 但如果你真的需要它,你可以做到。
除了John Gant的回答,您还可以检查datetime变量= Nothing(注意=而不是“is”)。 – NYSystemsAnalyst 2011-05-03 12:51:19
谢谢,使用Dim boolNotSet As Boolean = d =目前没有任何东西看起来是最简单的解决方案。有趣的可空铸件在 – Muleskinner 2011-05-03 13:02:09
@Chris之前从来没有见过 - 我认为他正在使用VB – 2011-05-03 13:22:13