C# 可空日期异常处理-有更好的方法吗
在尝试处理无效或空的日期输入时,我遇到了可空日期的挑战 对于普通C# 可空日期异常处理-有更好的方法吗,c#,.net,datetime,error-handling,C#,.net,Datetime,Error Handling,在尝试处理无效或空的日期输入时,我遇到了可空日期的挑战 对于普通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? nd = null; DateTime.TryParse(ctrlDa
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? nd = null;
DateTime.TryParse(ctrlDate.Text, out nd); //this doesn't work. it expects DateTime not DateTime?
日期时间?
与System.DateTime.TryParse(字符串,
out System.DateTime)具有一些无效参数
所以我不得不把它改成
DateTime? nd = null;
DateTime d = DateTime.Now;
if(DateTime.TryParse(ctrlDate.Text, out d))
nd = d;
我必须创建一个额外的DateTime
变量来实现可为空的日期
有更好的办法吗
DateTime d=新的DateTime.Now//您不能在这里分配null,为什么
因为它是一种值类型,是一种结构,所以不能为结构/值类型分配null
用于DateTime.TryParse
如果要使用
DateTime.TryParse
,则必须创建一个类型为DateTime
的额外变量,然后将其值指定给可为空的DateTime(如果需要) 您不需要为作为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是一种值类型,而不是引用类型。为什么不使用
DateTime.MinValue
除了可为空的类型之外?您确实需要创建额外的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;
}
为什么你需要在DateTime.TryParse
方法中使用它呢?@margabit我知道。我只是没有把它包括在问题中,他要求有可空的DateTime(DateTime?),我认为在不可空的情况下管理DateTime更容易。如果我们想知道它是否还未设置,我们可以检查值是否为!=DateTime.MinValue而不是与Null和casting进行比较。我关心的是可为Null的DateTime?
而不是DateTime
。我得到了System.DateTime.TryParse(string,out System.DateTime)具有一些正常的无效参数的最佳重载方法匹配。TryParse方法需要的是DateTime,而不是可为Null的DateTime,因此不能将其与可为Null的DateTime一起使用。我认为初始化局部变量是常见的做法?不,如果要将它们传递给使用out
参数的函数,则不需要。为变量赋值是毫无意义的,因为out
参数的全部要点是函数保证在该函数中赋值,并且在所有情况下都会替换初始值。这比mine@codingbiz,您不能使用可为空的日期时间,使用DateTime.TryParse方法,您可以编写自己的方法,对可为空的DateTime执行相同的操作