如何转换DateTime?到DateTime [英] How to convert DateTime? to DateTime
本文介绍了如何转换DateTime?到DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一个可空的DateTime( DateTime?
)转换为 DateTime
,但是我收到错误:
I want to convert a nullable DateTime (DateTime?
) to a DateTime
, but I am getting an error:
"Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?)"
我尝试了以下内容:
DateTime UpdatedTime = (DateTime)_objHotelPackageOrder.UpdatedDate == null
? DateTime.Now : _objHotelPackageOrder.UpdatedDate;
推荐答案
你想使用 null-coalescing运算符,这是专为此目的而设计的。
You want to use the null-coalescing operator, which is designed for exactly this purpose.
使用它,最终得到这个代码。
Using it you end up with this code.
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;
这篇关于如何转换DateTime?到DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文