1

可能重复:
首选哪个:Nullable<>.HasValue 或 Nullable<> == null?

我有领域DateTime? Date

我需要检查 Date 是否为空并设置最小值。

var anyDate = Date ?? DateTime.MinValue();

或者

var anyDate = Date.HasValue ? Date.Value : DateTime.MinValue();

什么是正确的 ?

4

2 回答 2

3

两者都是。第一个较短,然后有我的偏好。检查: 首选哪个:Nullable<>.HasValue 或 Nullable<>!= null?

于 2012-11-28T10:41:58.923 回答
1

我想你可以用这个

var anyDate = Date.GetValueOrDefault(DateTime.MinValue);

由于您要检查 null 并在这种情况下分配一个默认值,因此这大致转换为形式

if(Date.HasValue)
   return Date.Value;
return defaultvalue;
于 2012-11-28T10:56:40.757 回答