【发布时间】:2021-04-09 14:04:41
【问题描述】:
我正在努力学习 C#,但我真的很挣扎。我非常需要帮助。我有这个任务将语句包装在 try/catch 块中并让它打印“请输入一周中的实际日期”。如果发生错误,发送到控制台。我设法根据枚举确定用户输入是否为真,但我无法捕捉到错误的部分。任何帮助将不胜感激。
我在名为 OneWeek 的单独类中创建了枚举列表,这是我的代码:
Console.WriteLine("Please enter the current name of the day.");
string input = Console.ReadLine();
string test = input.ToLower();
OneWeek.DaysOfTheWeek dayParse;
bool inputParse = Enum.TryParse(test, out dayParse);
try
{
if (inputParse == true)
{
Console.WriteLine("Thank God it's " + input);
}
}
catch (FormatException)
{
Console.WriteLine("Please enter an actual day of the week.");
}
catch (Exception)
{
Console.WriteLine("Please enter an actual day of the week.");
}
Console.ReadLine();
return;
感谢所有回答的人!尝试了所有建议,它有所帮助。我还在建议的线程上找到了答案。你们让我很开心。谢谢!
这是我的代码的最终结果。只是改变了一些变量,但目标是一样的。
try
{
Console.WriteLine("Please enter the current name of the day.");
string input = Console.ReadLine();
string test = input.ToUpper();
OneWeek.DaysOfTheWeek day;
if (Enum.TryParse<OneWeek.DaysOfTheWeek>(test, out day))
{
Console.WriteLine("You are right! Today is " + test + "!");
}
else
{
throw new OverflowException();
}
}
catch (OverflowException)
{
Console.WriteLine("Please enter an actual day of the week.");
}
Console.ReadLine();
return;
【问题讨论】:
-
如果你使用
Enum.TryParse,你不需要try/catch,这个方法不会抛出,这就是它被创建的原因。 -
if (Enum.TryParse(Console.ReadLine(), out OneWeek.DaysOfTheWeek dayParse)){}else{}... TBH 你有很多不需要的变量,并且为了简单的检查而膨胀。 -
您不应该以这种方式使用异常。异常是针对实际发生的错误,而不是用于控制程序的流程。你有点暗示这一点:“我无法抓住虚假的部分”。这是因为您应该测试 false,而不是抛出异常。
-
即使我给出了答案,我也会补充,@tnw 是 100% 正确的。除了学习,别把这当成一个好策略。