简体   繁体   English

允许空的DateTime吗? 与C#中的DateTime变量进行变量比较

[英]Allow null DateTime? variable comparison with DateTime variable in C#

I have two variables of type DateTime and DateTime? 我有两个类型为DateTime和DateTime的变量?

DateTime StartDateFromDb;
DateTime? StartDateFromFilter;

if(StartDateFromDb.Date == StartDateFromFilter.Date);

While comparing, .Date is not allowingfor StartDateFromFilter of type allow null 比较时,.Date不允许类型为null的StartDateFromFilter

Thanks in advance 提前致谢

Use the Value property available as 使用可用的Value属性

  if(StartDateFromFilter.HasValue && StartDateFromDb.Date == StartDateFromFilter.Value.Date)

PS: Better to add a null value check. PS:最好添加一个空值检查。 StartDateFromFilter must have a value.(HasValue is true when DateTime? type variable is not null) StartDateFromFilter必须具有一个值。(当DateTime?类型变量不为null时,HasValue为true)

For any nullable type , you can use value property. 对于任何可为null的类型,您可以使用value属性。 StartDateFromFilter.Value.Date StartDateFromFilter.Value.Date

In your case , this should work fine 就您而言,这应该可以正常工作

if(StartDateFromDb.Date == StartDateFromFilter.Value.Date)
//// in this case .Date is not allowingfor StartDateFromFilter

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

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