gpt4 book ai didi

c# - 使用枚举和 switch 语句 c#

转载 作者:太空宇宙 更新时间:2023-11-03 17:33:54 25 4
gpt4 key购买 nike

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

我的枚举类

    public enum Options : byte
{
Display = 1,
Add,
Toggle,
Max,
Mean,
Medium,
Exit
}

在我的 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

在枚举中程序崩溃。
                switch (options)
{
case Options.Display: //dispaly regular time

case Options.Toggle://toggle

default:
Console.WriteLine("entry blah blah");
break;

最佳答案

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

关于c# - 使用枚举和 switch 语句 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8774261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com