解析日期和时间,try-catch,变量超出作用域数小时

本文关键字:作用域 小时 变量 try-catch 日期 时间 | 更新日期: 2023-09-27 18:15:44

我想解析日期和时间。我想要捕获是否有格式异常,我做以下操作:

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

然而,当我开始使用值'time'时,c#说"名称'time'在当前上下文中不存在"。我错在哪里?

解析日期和时间,try-catch,变量超出作用域数小时

您只在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!");
}