日期时间“空"价值 [英] DateTime "null" value

查看:36
本文介绍了日期时间“空"价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找,但找不到解决方案.您如何处理应该能够包含未初始化值(相当于 null)的 DateTime?我有一个可能设置了 DateTime 属性值的类.我正在考虑将属性持有者初始化为 DateTime.MinValue,然后可以轻松检查.我想这是一个很常见的问题,你是怎么做到的?

I've been searching a lot but couldn't find a solution. How do you deal with a DateTime that should be able to contain an uninitialized value (equivalent to null)? I have a class which might have a DateTime property value set or not. I was thinking of initializing the property holder to DateTime.MinValue, which then could easily be checked. I guess this is a quite common question, how do you do that?

推荐答案

对于普通的 DateTimes,如果你根本不初始化它们,它们将匹配 DateTime.MinValue,因为它是一个值类型而不是引用类型.

For normal DateTimes, if you don't initialize them at all then they will match DateTime.MinValue, because it is a value type rather than a reference type.

您也可以使用可为空的 DateTime,如下所示:

You can also use a nullable DateTime, like this:

DateTime? MyNullableDate;

或者更长的形式:

Nullable<DateTime> MyNullableDate;

最后,有一种内置方式可以引用任何类型的默认值.对于引用类型,这将返回 null,但对于我们的 DateTime 示例,它将返回与 DateTime.MinValue 相同的内容:

And, finally, there's a built in way to reference the default of any type. This returns null for reference types, but for our DateTime example it will return the same as DateTime.MinValue:

default(DateTime)

或者,在更新的 C# 版本中,

or, in more recent versions of C#,

default

这篇关于日期时间“空"价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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