问题描述
在VB.NET中,有没有办法将 DateTime
变量设置为未设置?为什么可以将 DateTime
设置为 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.
VB.Net中没有任何
相当于 default T)
在C#中:给定类型的默认值。
Nothing
in VB.Net is the equivalent of default(T)
in C#: the default value for the given type.
- 对于值类型,这本质上是相当于零:
0
整数
,False
对于Boolean
,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是DateTime
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 = code>
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
这篇关于为什么我不能检查“DateTime”是否为“Nothing”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!