我一直在寻找,但没有找到解决办法。如何处理应该能够包含未初始化值(相当于null)的DateTime ?我有一个类,它可能有一个DateTime属性值设置或没有。我正在考虑将属性持有人初始化为DateTime。MinValue,然后可以很容易地检查。我想这是一个很常见的问题,你是怎么做到的?


当前回答

下面的方法也可以

myClass.PublishDate = toPublish ? DateTime.Now : (DateTime?)null;

请注意属性PublishDate应该是DateTime?

其他回答

可以使用可空类。

DateTime? date = new DateTime?();

如果你使用。net 2.0(或更高版本),你可以使用可空类型:

DateTime? dt = null;

or

Nullable<DateTime> dt = null;

之后:

dt = new DateTime();

你可以用:

if (dt.HasValue)
{
  // Do something with dt.Value
}

或者你可以这样用:

DateTime dt2 = dt ?? DateTime.MinValue;

你可以在这里阅读更多: http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx

虽然每个人都已经给出了答案,但我将提到一种容易将datetime传递到函数中的方法

[ERROR:cannot convert system.datetime?]system.datetime)

DateTime? dt = null;
DateTime dte = Convert.ToDateTime(dt);

现在你可以在函数内部传递dte了,没有任何问题。

我有同样的问题,因为我必须给Null作为DateTime的参数,同时执行单元测试抛出ArgumentNullException。它在我的情况下工作,使用以下选项:

Assert.Throws<ArgumentNullException>(()=>sut.StartingDate = DateTime.Parse(null));

值得指出的是,虽然DateTime变量不能为空,但它仍然可以被比较为空而不会出现编译器错误:

DateTime date;
...
if(date == null) // <-- will never be 'true'
  ...