比较可空的DateTime? [英] Comparing nullable DateTime?

查看:99
本文介绍了比较可空的DateTime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



任何建议?

  // myobject.ExpireDatetime是DateTime? 
//
if(!myobject.ExpireDateTime.IsNull()&&&DateTime.Compare((DateTime)myobject.ExpireDateTime,DateTime.Now.ToUniversalTime())< 0)
{//错误!




编辑:对不起,混淆... myobject.ExpireDatetime是键入
DateTime。



解决方案

你的问题对我来说不是很清楚,如果我们有

  DateTime? ExpireDateTime; //可以是变量或属性

可以说只是

  if(ExpireDateTime< DateTime.UtcNow)
{
...
}

如果 ExpireDateTime null HasValue 为false)。一些没有经验的开发人员将很难理解解除操作员,所以为了更清楚,你可以写

  if(ExpireDateTime<(DateTime?)DateTime.UtcNow)
{
...
}

这是一样的,但更容易阅读和理解。



当然,如果可空的可能为null,则不要写入 .Value 。您将获得一个 InvalidOperationException 如果您这样做,可空对象必须具有值


Looking for a better way to compare a nullable date time than the following:

Any suggestions?

// myobject.ExpireDatetime is of DateTime?
//
if (!myobject.ExpireDateTime.IsNull() && DateTime.Compare((DateTime)myobject.ExpireDateTime, DateTime.Now.ToUniversalTime()) < 0)
{ //error! }    

Edited: Sorry for confusion...myobject.ExpireDatetime is of type DateTime.

解决方案

Your question is not quite clear to me, but if we have

DateTime? ExpireDateTime;  // could be a variable or a property

it's OK to say just

if (ExpireDateTime < DateTime.UtcNow)
{
  ...
}

This will be OK if ExpireDateTime is null (HasValue is false). Some inexperienced developers will struggle to understand lifted operators, so to make it more clear, you could write

if (ExpireDateTime < (DateTime?)DateTime.UtcNow)
{
  ...
}

It's the same, but easier to read and understand.

Never write .Value if the nullable might be null, of course. You will get an InvalidOperationException "Nullable object must have a value" if you do so.

这篇关于比较可空的DateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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