【问题标题】:What is the difference hasvalue operator check for null [duplicate]hasvalue运算符检查null有什么区别[重复]
【发布时间】:2012-11-16 04:31:34
【问题描述】:

可能重复:
Which is preferred: Nullable<>.HasValue or Nullable<> == null?

我有字段DateTime? Date

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

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

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

什么是对的?

【问题讨论】:

  • 两者都可以,但第二个的语义更好。

标签: c# nullable


【解决方案1】:

两者都是。第一个较短,然后有我的偏好。 查看 : Which is preferred: Nullable<>.HasValue or Nullable<> != null?

【讨论】:

    【解决方案2】:

    我觉得你可以用这个

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

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

    if(Date.HasValue)
       return Date.Value;
    return defaultvalue;
    

    【讨论】:

      猜你喜欢
      • 2010-10-15
      • 2014-08-10
      • 2017-05-27
      • 2016-04-28
      • 2011-01-02
      • 2013-06-16
      • 1970-01-01
      • 2022-06-10
      相关资源
      最近更新 更多