【问题标题】:How to set up try-catch to ensure user enters a value that is contained within an enum list?如何设置 try-catch 以确保用户输入包含在枚举列表中的值?
【发布时间】:2018-10-10 03:19:09
【问题描述】:

我有一个星期几的枚举列表,以及一个要求用户输入当前日期的程序(可以是列表中的任何一天)。我需要实现一个 try-catch 以确保用户输入一个有效的日期,但我遇到了一些困惑。

当我搜索如何使用枚举处理异常时,大多数网站建议使用 TryParse 而不是 try-catch,但是对于这个特定的任务,我需要将它包装在 try-catch 中。我应该使用 catch (OverflowException) 吗?这似乎不起作用,因为我不确定之后会发生什么。我试图在 OverflowException 之后声明一个变量,因为这就是我在 try-catch 示例中看到的;但是,我把它拿出来,因为它给了我错误。到目前为止,我还没有找到与我类似的使用 try-catch 的示例,我可以从中学习。

有人可以看看这个程序并帮助我如何正确地包含一个 try-catch 来处理无效输入吗?如果用户输入星期日到星期六以外的任何内容(包括缩写),我希望控制台说“无效日期”。谢谢!!

 class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Please enter the current day of the week.");
                string currentday = Console.ReadLine();
                Console.WriteLine("Good job.  Today is " + currentday);
                Console.ReadLine();

            }
           catch(OverflowException)
            {
                Console.WriteLine("Not a valid day");
            }
            Console.ReadLine();
        }

        public enum days
        {
            Sunday,
            Monday,
            Tuesday,
            Wednesday,
            Thursday,
            Friday,
            Saturday          
        }

【问题讨论】:

  • 为什么只测试 OverflowException?
  • 您当前的代码永远不会抛出异常。因为您不转换输入。
  • Poul Bak 我不确定还要测试什么。我看到在网上的一个例子中使用了溢出异常,所以我想我应该从那里开始看看发生了什么。我应该将输入转换为枚举吗?
  • 嗯,这不是你想要的吗?你当然可以把它保存为字符串,这样就不会出错了。
  • 谢谢你,波尔!我太新了,我什至没有意识到转换为枚举是一种选择;我认为它应该只是一个字符串,所以我会像你提到的那样保持它的字符串。

标签: c# enums


【解决方案1】:

您可以使用EnumTryParse Method。您实际上也可以删除 try-catch。

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("Please enter the current day of the week.");
            string currentday = Console.ReadLine();
            days day;

            if (Enum.TryParse<days>(currentday, out day))
            {
                Console.WriteLine("Good job.  Today is " + currentday);
                Console.ReadLine();
            }
            else
            {
                throw new OverflowException(); // try parse failed. enum not valid! Why OverflowException?
            }
        }
        catch (OverflowException)
        {
            Console.WriteLine("Not a valid day");
        }
        Console.ReadLine();
    }

    public enum days
    {
        Sunday,
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday
    }
}

或

static void Main(string[] args)
{
    Console.WriteLine("Please enter the current day of the week.");
    string currentday = Console.ReadLine();
    days day;

    if (Enum.TryParse<days>(currentday, out day))
    {
        Console.WriteLine("Good job.  Today is " + currentday);
    }
    else
    {
       Console.WriteLine("Not a valid day");
    }

    Console.ReadLine();
}

编辑:

经进一步检查,@Nalaka526 的回答更合适。 Enum.TryParse 将针对“01”、“111”等意外输入返回 true,而 Enum.IsDefined 将仅匹配枚举名称。

这是您在输入有效之前继续提示当天的一种方式。

static void Main(string[] args)
{
    bool isValid = false;

    do {
        Console.WriteLine("Please enter the current day of the week.");
        string currentday = Console.ReadLine();

        isValid = Enum.IsDefined(typeof(days), currentday);

        if (isValid)
        {
            Console.WriteLine("Good job.  Today is " + currentday);
        }
        else
        {
            Console.WriteLine("Not a valid day");
        }
    } while (!isValid);            

    Console.ReadLine();
}

【讨论】:

  • 谢谢你,约翰!这些看起来都是很棒的解决方案,而且您已经编写了它们,因此我很容易理解和理解它们。这是完美的,谢谢:)
  • 你好约翰!不确定您是否会看到这一点,但我决定采用您的第二个解决方案,因为我的基本知识水平更容易理解。如果他们的输入无效,我还想提示用户输入另一天。在这种情况下,您是否建议使用“do-while”循环?我正在尝试放置一个,但它似乎不起作用,因为我不确定如何编写一个查看枚举列表并评估有效输入的布尔值。有没有办法在这里添加循环功能?再次感谢你!您的帮助非常宝贵!
  • 非常感谢,约翰!这是如此简单和简洁。最重要的是,它有效!非常感谢:)
【解决方案2】:

也可以使用Enum.IsDefined(不使用Try/Catch)检查输入的值是否有效,

Console.WriteLine("Please enter the current day of the week.");
string currentday = Console.ReadLine();

if (Enum.IsDefined(typeof(days), currentday))
    Console.WriteLine("Good job.  Today is " + currentday);
else
    Console.WriteLine("Not a valid day");

Console.ReadLine();

【讨论】:

  • 谢谢,纳拉卡!!这是一个如此简洁且非常有用的解决方案!我开始看到可以实现不同的异常处理方式:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-30
  • 1970-01-01
相关资源
最近更新 更多