【问题标题】:DateTime.hasvalue vs datetime == null, which one is better and why [duplicate]DateTime.hasvalue vs datetime == null,哪个更好以及为什么[重复]
【发布时间】:2016-10-29 16:22:17
【问题描述】:

我想问一个关于控制日期时间的空值的问题。

if (mydatetime != null)

if(mydatetime.hasvalue)

哪个更好,哪个更合适,为什么?

谢谢。

【问题讨论】:

  • 它们并不完全相同。 HasValue 仅当 var 为 Nullable 时才有效
  • 第一个如果有值则为真,第二个如果没有值则为真。 ! 可能太多了。
  • 我的是可以为空的datetime(datetime?my datetime=null),这种情况下有什么区别吗?
  • @Aurora 没有区别,保持一致

标签: c# performance datetime null


【解决方案1】:

!=null 的第一个比较是有效的比较,而第二个只能在变量声明为Nullable 时使用,或者换句话说,与.HasValue 的比较只能在DateTime 变量声明为时使用可以为空

例如:

DateTime dateInput; 
// Will set the value dynamically
if (dateInput != null)
{ 
   // Is a valid comparison         
}
if (dateInput.HasValue)
{ 
   // Is not a valid comparison this time        
}

在哪里

DateTime? dateInput; // nullable declaration
// Will set the value dynamically
if (dateInput != null)
{ 
   // Is a valid comparison         
}
if (dateInput.HasValue)
{ 
   // Is also valid comparison this time        
}

【讨论】:

    【解决方案2】:

    如果你问

    if (mydatetime != null) 
    

    您正在检查变量是否已被实例化。

    如果它实际上是没有实例化,下面的语句会给你 NullReferenceException

    if(!mydatetime.hasvalue)
    

    因为您试图访问 null 对象的属性

    仅当您将DateTime 声明为Nullable 时,它才会显示相同的行为。

    Nullable<DateTime> mydatetime = null;
    
    Console.WriteLine(mydatetime.HasValue);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 2017-03-30
      • 2013-12-28
      相关资源
      最近更新 更多