简体   繁体   English

DateTime.Ticks为可为空的日期时间

[英]DateTime.Ticks for nullable datetime

In my app, article.DatePublished is a nullable DateTime field. 在我的应用程序中,article.DatePublished是一个可以为空的DateTime字段。 Now I have this following code: 现在我有以下代码:

      list.Add(article.DatePublished.Ticks);

Here I am getting a compile error as Ticks property does not work with nullable DateTimes. 在这里我得到一个编译错误,因为Ticks属性不适用于可空的DateTimes。

One way of handling this is: 处理此问题的一种方法是:

if (article.DatePublished != null)
      list.Add(((DateTime)article.DatePublished).Ticks);

This works, but is this an elegant solution? 这有效,但这是一个优雅的解决方案吗? Or can we make it "better"? 或者我们可以让它“更好”吗?

Thanks, 谢谢,

Vivek 维韦克

You need to get at the .Value property of the DateTime? 你需要获得DateTime?.Value属性DateTime? .

if (nullableDate != null) // or if (nullableDate.HasValue)
    ticks = nullableDate.Value.Ticks;

You could otherwise use nullableDate.GetValueOrDefault().Ticks , which would normalize a null date into the default value of DateTime , which is DateTime.MinValue . 否则你可以使用nullableDate.GetValueOrDefault().Ticks ,它会将null日期规范化为DateTime的默认值,即DateTime.MinValue

As Icarus mentioned, I'd use: 正如伊卡洛斯所说,我会用:

if (article.DatePublished != null)
{
    list.Add(article.DatePublished.Value.Ticks);
}

Or even: 甚至:

if (article.DatePublished.HasValue)
{
    list.Add(article.DatePublished.Value.Ticks);
}

Depending on what you're trying to do, it could be that LINQ will give you simpler code: 根据您要做的事情,可能是LINQ会为您提供更简单的代码:

var list = articles.Select(article => article.DatePublished)
                   .Where(date => date != null)
                   .Select(date => date.Ticks)
                   .ToList();
if (article.DatePublished.HasValue)
{
      list.Add(article.DatePublished.Value.Ticks);
}

If you always want to add a value, including a default if DatePublished is null, you could do something like 如果你总是想要添加一个值,包括默认值,如果DatePublished为null,你可以做类似的事情

var date = article.DatePublished ?? new DateTime(whatever);
list.Add(date.Ticks);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM