Mul*_*ner 75 vb.net null datetime nullable nothing
在VB.NET中,有没有办法将DateTime变量设置为"未设置"?为什么它可以设置DateTime到Nothing,但没有能够检查它是否是Nothing?例如:
Dim d As DateTime = Nothing
Dim boolNotSet As Boolean = d Is Nothing
Run Code Online (Sandbox Code Playgroud)
第二个语句抛出此错误:
'Is' operator does not accept operands of type 'Date'. Operands must be reference or
nullable types.
Run Code Online (Sandbox Code Playgroud)
jer*_*enh 134
这是与VB.Net,IMO混淆的最大原因之一.
Nothing在VB.Net中相当于default(T)C#:给定类型的默认值.
0for Integer,Falsefor Boolean,DateTime.MinValuefor DateTime,...null值(引用的引用,没有任何内容).d Is Nothing因此d Is DateTime.MinValue,该陈述相当于,显然无法编译.
解决方案:正如其他人所说
DateTime?(即Nullable(Of DateTime)).这是我的首选解决方案.d = DateTime.MinValue或等效d = Nothing在原始代码的上下文中,您可以使用:
Dim d As DateTime? = Nothing
Dim boolNotSet As Boolean = d.HasValue
Run Code Online (Sandbox Code Playgroud)
可以在Anthony D. Green的博客上找到更全面的解释
DateTime 是一个值类型,这意味着它总是有一些值。
它就像一个整数 - 它可以是 0、或 1、或小于零,但它永远不可能是“无”。
如果您想要一个可以取值 Nothing 的 DateTime,请使用 Nullable DateTime。