在尝试处理无效或空日期输入时,我遇到了这个问题。
对于普通的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;
}发布于 2012-09-20 07:19:56
不需要将任何内容赋值给作为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是一个值类型,而不是一个引用类型。
发布于 2012-09-20 07:19:28
DateTime d=新的DateTime.Now;//您不能在这里赋值为null,为什么?
因为它是一个值类型,它是一个结构,所以不能将null赋值给结构/值类型。
对于DateTime.TryParse
如果您想使用DateTime.TryParse,那么您必须创建一个类型为DateTime的额外变量,然后如果您愿意的话,将它的值分配给可空的DateTime。
https://stackoverflow.com/questions/12507716
复制相似问题