DateTime.Hasvalue vs datetime == null,哪个更好,为什么?

本文关键字:更好 为什么 null Hasvalue vs datetime DateTime | 更新日期: 2023-09-27 17:52:13

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

if (mydatetime != null)

if(mydatetime.hasvalue)

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

谢谢。

DateTime.Hasvalue vs datetime == null,哪个更好,为什么?

!=null的第一次比较是有效的比较,而第二次比较只能在变量声明为空时使用,或者换句话说,与.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        
}

如果你问

if (mydatetime != null) 

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

如果它实际上是而不是实例化,下面的语句将给你a NullReferenceException

if(!mydatetime.hasvalue)

因为您正在尝试访问null对象的属性

只有当你声明DateTimeNullable时,它才会显示相同的行为。

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