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


当前回答

问题本身给出了正确的答案。“如果datetime为空,你如何处理它?”,提问者在最后用datetime . minvalue给出答案。我的想法是提问者的方式应该是不变的。我建议使用DateTime。MaxValue比较,因为它不会发生直到12/31/9999。如果为真,则将field显示为日期以外的其他内容。下面是一个例子;

 DateNotified = DBNull.Value.Equals(reader["DateNotified"])? Convert.ToDateTime(reader["DateNotified"]): DateTime.MaxValue

在前端 如果你使用的是网格,那么;

columns.Add(col => col.DateNotified).Css("text-right").Titled("Date Notified").RenderValueAs(c => c.DateNotified.ToString("MM/dd/yyyy").Equals(DateTime.MaxValue) ? "":c.DateNotified.ToString("MM/dd/yyyy"));

或者一个简单的观点

@Model.DateNotified.ToString("MM/dd/yyyy").Equals(DateTime.MaxValue) ? "":Model.DateNotified.ToString("MM/dd/yyyy")

其他回答

问题本身给出了正确的答案。“如果datetime为空,你如何处理它?”,提问者在最后用datetime . minvalue给出答案。我的想法是提问者的方式应该是不变的。我建议使用DateTime。MaxValue比较,因为它不会发生直到12/31/9999。如果为真,则将field显示为日期以外的其他内容。下面是一个例子;

 DateNotified = DBNull.Value.Equals(reader["DateNotified"])? Convert.ToDateTime(reader["DateNotified"]): DateTime.MaxValue

在前端 如果你使用的是网格,那么;

columns.Add(col => col.DateNotified).Css("text-right").Titled("Date Notified").RenderValueAs(c => c.DateNotified.ToString("MM/dd/yyyy").Equals(DateTime.MaxValue) ? "":c.DateNotified.ToString("MM/dd/yyyy"));

或者一个简单的观点

@Model.DateNotified.ToString("MM/dd/yyyy").Equals(DateTime.MaxValue) ? "":Model.DateNotified.ToString("MM/dd/yyyy")

DateTime ?MyDateTime{拿套;}

MyDateTime = (dr["f1"] == DBNull.Value) ? (DateTime?)null : ((DateTime)dr["f1"]);

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

你也可以使用一个可空的DateTime,像这样:

DateTime? MyNullableDate;

或较长的形式:

Nullable<DateTime> MyNullableDate;

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

default(DateTime)

或者,在c#的最新版本中,

default

我会考虑使用可空类型。

DateTime吗?myDate而不是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