在尝试处理无效或空日期输入时,我遇到了Nullable日期的挑战
对于普通DateTime
变量,我可以这样做
DateTime d = new DateTime.Now; //You can also use DateTime.MinValue. You cannot assign null here, WHY?
DateTime.TryParse(ctrlDate.Text, out d);
可以为Nullable DateTime
DateTime? nd = null;
DateTime.TryParse(ctrlDate.Text, out nd); //this doesn't work. it expects DateTime not DateTime?
对于DateTime?
System.DateTime.TryParse的最佳重载方法匹配(字符串, out System.DateTime)有一些无效的参数
所以我不得不把它改成
DateTime? nd = null;
DateTime d = DateTime.Now;
if(DateTime.TryParse(ctrlDate.Text, out d))
nd = d;
我必须创建一个额外的DateTime
变量来实现可以为空的日期。
有更好的方法吗?
答案 0 :(得分:4)
您不需要为作为out
参数传递给方法的变量赋予任何内容,只需:
DateTime d;
if (DateTime.TryParse(ctrlDate.Text, out d))
{
// the date was successfully parsed => use it here
}
else
{
// tell the user to enter a valid date
}
至于你的第一个问题,为什么你不能写DateTime d = null;
,这是因为DateTime是一个值类型,而不是一个引用类型。
答案 1 :(得分:2)
DateTime d = new DateTime.Now; //你不能在这里指定null,为什么?
因为它的值类型是一个结构,所以不能将null赋给结构/值类型。
对于DateTime.TryParse
如果要使用DateTime.TryParse
,则必须创建类型为DateTime
的额外变量,然后根据需要将其值分配给Nullable DateTime。
答案 2 :(得分:2)
您确实需要创建额外的DateTime
变量,没有更好的方法。
虽然您当然可以将其封装在您自己的解析方法中:
bool MyDateTimeTryParse(string text, out DateTime? result)
{
result = null;
// We allow an empty string for null (could also use IsNullOrWhitespace)
if (String.IsNullOrEmpty(text)) return true;
DateTime d;
if (!DateTime.TryParse(text, out d)) return false;
result = d;
return true;
}
答案 3 :(得分:0)
为什么不使用
DateTime.MinValue
而不是可空类型?