【问题标题】:Parsing date and time, try-catch, variable for hours out of scope解析日期和时间,try-catch,变量超出范围
【发布时间】:2015-10-03 08:58:23
【问题描述】:

我想解析日期和时间。如果有格式异常,我想捕获并执行以下操作:

    try
    {
        DateTime time = DateTime.Parse(Console.ReadLine());
    }
    catch (FormatException)
    {
        Console.WriteLine("Wrong date and time format!");
    }

但是,当我开始使用值 'time' 时,C# 会说“名称 'time' 在当前上下文中不存在”。我的错在哪里?

【问题讨论】:

    标签: c# date parsing time


    【解决方案1】:

    您只在try 块中声明了time,因此之后它就超出了范围。你可以事先声明:

    DateTime time;
    try
    {
        time = ...;
    }
    catch (FormatException)
    {
        Console.WriteLine("Wrong date and time format!");
        return; // Or some other way of getting out of the method,
                // otherwise time won't be definitely assigned afterwards
    }
    

    但是,最好使用DateTime.TryParse 而不是捕获FormatException

    DateTime time;
    if (DateTime.TryParse(Console.ReadLine(), out time)
    {
        // Use time
    }
    else
    {
        Console.WriteLine("Wrong date and time format!");
    }
    

    【讨论】:

    • 绝妙的答案!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多