Why can't I check if a 'DateTime' is 'Nothing'?

前端 未结 8 2046
天命终不由人
天命终不由人 2020-12-07 17:18

In VB.NET, is there a way to set a DateTime variable to \"not set\"? And why is it possible to set a DateTime to Nothing, but not<

8条回答
  •  一生所求
    2020-12-07 17:44

    In any programming language, be careful when using Nulls. The example above shows another issue. If you use a type of Nullable, that means that the variables instantiated from that type can hold the value System.DBNull.Value; not that it has changed the interpretation of setting the value to default using "= Nothing" or that the Object of the value can now support a null reference. Just a warning... happy coding!

    You could create a separate class containing a value type. An object created from such a class would be a reference type, which could be assigned Nothing. An example:

    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
    

    End Class

    'in 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()
    
        ' Output:
        'test1:  Succeeded()
        'test2:  Failed()
        '.ToString() = 4/10/2012 11:28:10 AM
        '.Value.ToString() = 4/10/2012 11:28:10 AM
    

    Then you could pick and choose overridables to make it do what you need. Lot of work - but if you really need it, you can do it.

提交回复
热议问题