在 VB.NET 中,以下代码:
Dim myBool As Boolean = False
Dim myDate As Date? = If(myBool, Date.Today, Nothing)
Console.WriteLine(myDate)
生产:
1/1/0001 12:00:00 AM
但是,如果我将其写为:
Dim myBool As Boolean = False
Dim myDate As Date?
If myBool Then
myDate = Date.Today
Else
myDate = Nothing
End If
Console.WriteLine(myDate)
然后它会如预期那样打印 null/nothing。
这里发生了什么,我怎样才能用一个单行代码将日期或 null 分配给 VB.NET 中的可空 DateTime,而实际上又不默认为
01/01/0001 12:00:00 AM
?
If(myBool, Date.Today, Nothing)
表达式必须独立存在,并且在没有任何来自赋值左侧的输入的情况下进行计算。因此,表达式的结果是一个标准(不可为空)DateTime
值,其中Nothing
被解释为默认的1/1/0001 12:00:00 AM
。
要创建所需的结果,您可以这样做:
If(myBool, Date.Today, CType(Nothing, DateTime?))
或者这个:
If(myBool, Date.Today, New Nullable(Of Date))