为什么我不能检查“DateTime"是否为“Nothing"? [英] Why can't I check if a 'DateTime' is 'Nothing'?
问题描述
在 VB.NET 中,有没有办法将 DateTime
变量设置为未设置"?为什么可以将 DateTime
设置为 Nothing
,但不能检查它是否是 Nothing
?例如:
In VB.NET, is there a way to set a DateTime
variable to "not set"? And why is it possible to set a DateTime
to Nothing
, but not possible to check if it is Nothing
? For example:
Dim d As DateTime = Nothing
Dim boolNotSet As Boolean = d Is Nothing
第二条语句抛出这个错误:
The second statement throws this error:
'Is' operator does not accept operands of type 'Date'. Operands must be reference or
nullable types.
推荐答案
这是与 VB.Net、IMO 混淆的最大来源之一.
This is one of the biggest sources of confusion with VB.Net, IMO.
Nothing
相当于 C# 中的 default(T)
:给定类型的默认值.
Nothing
in VB.Net is the equivalent of default(T)
in C#: the default value for the given type.
- 对于值类型,这本质上相当于零":
0
表示Integer
,False
表示Boolean
code>,DateTime.MinValue
forDateTime
, ... - 对于引用类型,它是
null
值(一个引用,好吧,什么都不引用).
- For value types, this is essentially the equivalent of 'zero':
0
forInteger
,False
forBoolean
,DateTime.MinValue
forDateTime
, ... - For reference types, it is the
null
value (a reference that refers to, well, nothing).
语句d Is Nothing
因此等价于d Is DateTime.MinValue
,显然不能编译.
The statement d Is Nothing
is therefore equivalent to d Is DateTime.MinValue
, which obviously does not compile.
解决方案:正如其他人所说
Solutions: as others have said
- 要么使用
DateTime?
(即Nullable(Of DateTime)
).这是我首选的解决方案. - 或使用
d = DateTime.MinValue
或等效的d = Nothing
- Either use
DateTime?
(i.e.Nullable(Of DateTime)
). This is my preferred solution. - Or use
d = DateTime.MinValue
or equivalentlyd = Nothing
在原始代码的上下文中,您可以使用:
In the context of the original code, you could use:
Dim d As DateTime? = Nothing
Dim boolNotSet As Boolean = d.HasValue
更全面的解释可以在安东尼 D. 格林的博客
这篇关于为什么我不能检查“DateTime"是否为“Nothing"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!