【问题标题】:Nullable dates exception handling - is there a better way可空日期异常处理 - 有没有更好的方法
【发布时间】:2012-09-20 07:17:03
【问题描述】:

在尝试处理无效或空日期输入时,我遇到了 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);

对于可空日期时间

DateTime? nd = null;
DateTime.TryParse(ctrlDate.Text, out nd); //this doesn't work. it expects DateTime not 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 变量来实现这个可空日期。

有没有更好的办法?

【问题讨论】:

    标签: c# .net datetime error-handling


    【解决方案1】:

    您无需为作为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? 而不是DateTime。我得到 System.DateTime.TryParse(string, out System.DateTime) 的最佳重载方法匹配有一些无效参数
    • 这很正常。 TryParse 方法需要一个 DateTime,而不是可为空的 DateTime,因此您不能将它与可为空的 DateTime 一起使用。
    • 我认为初始化局部变量是常见的做法?
    • 不,如果您打算将它们传递给与 out 参数一起使用的函数,则不会。给变量赋值绝对没有意义,因为out 参数的全部意义在于该函数保证您将在该函数内部分配一个值,并且您的初始值将被替换在所有情况下。
    • 这比我的更有意义
    【解决方案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】:

      日期时间 d = 新的日期时间。现在; //这里不能赋值null,为什么?

      因为它是一个值类型,它是一个结构,所以您不能将 null 分配给结构/值类型。

      对于 DateTime.TryParse

      如果您想使用DateTime.TryParse,那么您必须创建一个DateTime 类型的额外变量,然后如果您愿意,将其值分配给Nullable DateTime。

      【讨论】:

      • @codingbiz,你不能使用 Nullable DateTime,你的 DateTime.TryParse 方法,你可以编写自己的方法为 Nullable DateTime 做同样的事情
      【解决方案4】:

      为什么不使用

      DateTime.MinValue 
      

      而不是可空类型?

      【讨论】:

      • 为什么需要将它与DateTime.TryParse 方法一起使用?
      • @margabit 我知道。我只是没有在问题中包含它
      • 他要求拥有可为空的 DateTime(DateTime?),我认为在不可以为空的情况下管理 DateTime 更容易。如果我们想知道它是否没有被设置,我们可以检查 if value != DateTime.MinValue 而不是与 Null 进行比较和强制转换。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      • 2011-07-30
      相关资源
      最近更新 更多