为什么我不能检查'DateTime'是否'没什么'?

Mul*_*ner 75 vb.net null datetime nullable nothing

在VB.NET中,有没有办法将DateTime变量设置为"未设置"?为什么它可以设置DateTimeNothing,但没有能够检查它是否是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的博客上找到更全面的解释


Joh*_*ant 10

DateTime是一个值类型,这就是它不能为null的原因.您可以检查它是否相等DateTime.MinValue,或者您可以使用它Nullable(Of DateTime).

VB有时"有帮助"会让你认为它正在做一些事情.当它允许你将Date设置为Nothing时,它实际上将它设置为其他值,可能是MinValue.

有关值类型与引用类型的广泛讨论,请参阅此问题.


Che*_*eso 5

DateTime 是一个值类型,这意味着它总是有一些值。

它就像一个整数 - 它可以是 0、或 1、或小于零,但它永远不可能是“无”。

如果您想要一个可以取值 Nothing 的 DateTime,请使用 Nullable DateTime。