为什么我不能检查“DateTime”是否为“Nothing”? [英] Why can't I check if a 'DateTime' is 'Nothing'?

查看:184
本文介绍了为什么我不能检查“DateTime”是否为“Nothing”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 for DateTime ,..

  • 对于引用类型,它是 null 值(引用,没有什么)

  • For value types, this is essentially the equivalent of 'zero': 0 for Integer, False for Boolean, DateTime.MinValue for DateTime, ...
  • 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 equivalently d = Nothing

在原始代码的上下文中,您可以使用:

In the context of the original code, you could use:

Dim d As DateTime? = Nothing
Dim boolNotSet As Boolean = d.HasValue

这篇关于为什么我不能检查“DateTime”是否为“Nothing”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆