Nullable type and if issue

前端 未结 4 1261
暖寄归人
暖寄归人 2020-12-21 05:08

Here is simplest piece of code

Dim testInvoiceDate As DateTime? = If(String.IsNullOrEmpty(Nothing),
                                      Nothing,
                   


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-21 05:33

    That compiles in VB.NET(as opposed to C#) because here Nothing has multiple meanings.

    1. null
    2. default value for that type

    In this case the compiler uses the second option since there is otherwise no implicit conversion between the DateTime and Nothing(in the meaning of null).

    The default value of DateTime(a Structure which is a value type) is #1/1/0001 12:00:00 AM#

    You could use this to get a Nullable(Of DateTime):

    Dim testInvoiceDate As DateTime? = If(String.IsNullOrEmpty(Nothing), New Nullable(Of Date), New DateTime(2018, 3, 20))
    

    or use an If:

    Dim testInvoiceDate As DateTime? = Nothing
    If Not String.IsNullOrEmpty(Nothing) Then testInvoiceDate = New DateTime(2018, 3, 20)
    

提交回复
热议问题