getset属性中的Nullable Datetime

时间:2016-10-13 23:30:03

标签: asp.net vb.net

Sub Main()
    Dim e As Example = New Example()
    ' Set property.
    If Date.TryParse("Null", e.Number) Then
        'get the valid date
        '10/12/2016'
    Else
        'get the value as nothing
        'Nothing
    End If
    ' Get property.
    Console.WriteLine(e.Number)
    Console.ReadKey()
End Sub

Class Example
    Private _count As Date

    Public Property Number() As Date
        Get
            Return _count
        End Get
        Set(ByVal value As Date)
            _count = value
        End Set
    End Property
End Class

如果日期有效,我想获得正确的日期,否则我需要在e.number中存储Nothing或null 注意: - 我应该在e.number中获得值

1 个答案:

答案 0 :(得分:1)

您需要声明您的属性可以为空,这意味着使用Nullable(Of Date)或速记Date?。然后你可以这样做:

If Date.TryParse(myString, myDate) Then
    myObject.MyNullableDateProperty = myDate
Else
    myObject.MyNullableDateProperty = Nothing
End If

当需要使用可空值类型时,必须首先使用其HasValue属性来确定是否有要使用的值,然后从其Value属性中获取该值,例如

If myObject.MyNullableDateProperty.HasValue Then
    Console.WriteLine("The date is " & myObject.MyNullableDateProperty.Value.ToString())
Else
    Console.WriteLine("There is no date")
End If