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

Aur*_*ora 5 c# performance null datetime

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

if (mydatetime != null)
Run Code Online (Sandbox Code Playgroud)

或者

if(mydatetime.hasvalue)
Run Code Online (Sandbox Code Playgroud)

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

谢谢你。

suj*_*lil 5

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

例如 :

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

然而

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        
}
Run Code Online (Sandbox Code Playgroud)


Mon*_*Zhu 3

如果你问

if (mydatetime != null) 
Run Code Online (Sandbox Code Playgroud)

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

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

if(!mydatetime.hasvalue)
Run Code Online (Sandbox Code Playgroud)

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

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

Nullable<DateTime> mydatetime = null;

Console.WriteLine(mydatetime.HasValue);
Run Code Online (Sandbox Code Playgroud)