使用enum和switch语句c#

Aar*_*ron 1 c# enums switch-statement

我使用枚举作为我的switch语句的选项,它的工作原理.问题是如果用户输入无效选项,程序崩溃.我应该添加什么以便使用默认值?

我的枚举课

    public enum Options : byte
    {
        Display = 1,
        Add,
        Toggle,
        Max,
        Mean,
        Medium,
        Exit
    }
Run Code Online (Sandbox Code Playgroud)

在主我的switch语句中

    string volString = Console.ReadLine();
    Options options = (Options)Enum.Parse(typeof(Options), volString);
    // this is the line that is giving me the runtime error. Since other options are not found
Run Code Online (Sandbox Code Playgroud)

在枚举程序崩溃.

                switch (options)
                {
                    case Options.Display: //dispaly regular time

                    case Options.Toggle://toggle 

                    default:
                        Console.WriteLine("entry blah blah");
                        break;
Run Code Online (Sandbox Code Playgroud)

Mik*_*han 5

而不是Enum.Parse使用Enum.TryParse...这将返回一个布尔值来说明文本是否可以转换为您的枚举.如果确实运行了您的开关,则通知用户他们输入的字符串无效.