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

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

问题描述

寻找更好的方式来比较可为空的日期时间比下面:



任何建议

  // myobject.ExpireDatetime是日期时间? 
//
如果(myobject.ExpireDateTime.IsNull()及!&安培; DateTime.Compare((日期时间)myobject.ExpireDateTime,DateTime.Now.ToUniversalTime())小于0)
{//错误! }




编辑:对不起混乱...... myobject.ExpireDatetime是类型
日期时间。



解决方案

您的问题不是很清楚,我,但如果我们有

 日期时间? ExpireDateTime; //可能是一个变量或属性



这是确定的说只是

 如果(ExpireDateTime< D​​ateTime.UtcNow)
{

}

这将是确定的,如果 ExpireDateTime 的HasValue 是假的)。一些没有经验的开发商将很难理解解除运营商,所以要更清楚,你可以写

 如果(ExpireDateTime<(DATETIME)DateTime.UtcNow)
{

}

这是相同的,但更容易阅读和理解。<​​/ p>

从不的写 .value的如果为空的可能是空的,当然。如果你这样做,你会得到一个NullReferenceException。


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'll get a NullReferenceException if you do so.

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

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