我想提出一个关于控制日期时间的空值的问题。
哪个更好,或者说更合适,为什么?谢谢。
if (mydatetime != null)
或者
if(mydatetime.hasvalue)
哪个更好,或者说更合适,为什么?谢谢。
if (mydatetime != null)
或者
if(mydatetime.hasvalue)
与!=null
的第一个比较是有效的比较,而第二个比较只能在变量声明为Nullable时使用,换句话说,只有在DateTime变量声明为Nullable时才能使用.HasValue
进行比较。
例如:
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)
您正在检查变量是否已被实例化。
如果它没有被实例化,下面的语句将会给您一个NullReferenceException
。
if(!mydatetime.hasvalue)
因为您试图访问一个null
对象的属性。
只有在将DateTime
声明为Nullable
时,它才会显示相同的行为。
Nullable<DateTime> mydatetime = null;
Console.WriteLine(mydatetime.HasValue);
HasValue
仅适用于变量为Nullable的情况。 - Ňɏssa Pøngjǣrdenlarp!
。 - René Vogt