在尝试处理无效或空日期输入时,我遇到了这个问题。
对于普通的DateTime变量,我可以这样做
DateTime d = new DateTime.Now; //You can also use DateTime.MinValue. You cannot assign null here, WHY?
DateTime.TryParse(ctrlDate.Text, out d);对于可空的DateTime
DateTime? nd = null;
DateTime.TryParse(ctrlDate.Text, out nd); //this doesn't work. it expects DateTime not DateTime?For DateTime? System.DateTime.TryParse(string,out System.DateTime)的最佳重载方法匹配有一些无效的参数
所以我不得不把它改成
DateTime? nd = null;
DateTime d = DateTime.Now;
if(DateTime.TryParse(ctrlDate.Text, out d))
nd = d;为了实现可空日期,我必须创建一个额外的DateTime变量。
有更好的办法吗?
发布于 2012-09-20 07:35:19
您确实需要创建额外的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;
}https://stackoverflow.com/questions/12507716
复制相似问题