c# - 为什么在 C# 中,在默认情况下切换循环中需要 break?

标签 c# switch-statement default break

<分区>

default 之后,控制应该自动从switch loop 中出来。但是 C# 需要使用 break 语句吗?为什么在 C# 中控件在 default 之后不会自动跳出 switch loop

下面的微软文档是这样说的:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch

在我的代码中:

using System;

class Program {
static void Main() {
    Console.WriteLine("Enter a number between 1 and 10");
    int num;
    bool validity = int.TryParse(Console.ReadLine(), out num);
    if(validity==true) {
        switch(num) {
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:

                Console.WriteLine("You have entered {0}", num);
                break;
            default:
                Console.WriteLine("You have not entered a number between 1 and 10");
                //break; This part is commented
        }
    } 
    else {
        Console.WriteLine("Please make a valid input");
    }
}
} 

它给了我错误-

(23,5): error CS8070: Control cannot fall out of switch from final case label ('default:')

但是在取消注释 break 部分时代码工作正常。

最佳答案

switch(num) {
    case 1:
        DoSomething();
    case 2:
        DoSomething2();
    case 3:
    case 4:
    case 5:
        Console.WriteLine("You have entered {0}", num);
        break;
    default:
        Console.WriteLine("You have not entered a number between 1 and 10");
        //break; This part is commented
    case 6:
        DoSomething3();
}

在上述情况 1 的代码中,您只需要 DoSomething()DoSomething() 并转到情况 2?避免这样的错误(忘记休息)。

您可以在 default 之后阻止另一个案例,您可以忘记添加中断。

关于c# - 为什么在 C# 中,在默认情况下切换循环中需要 break?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47938715/

相关文章:

C 将 const char * 转换为 char

python - 如何使用默认属性描述符并从 __init__() 成功分配?

c# - 跟踪 Observable 中的(数量)观察者?

c# - 将 Entity Framework 4.4 与 Mysql 结合使用

c# - 我可以在 Windows 8 操作系统上使用 C# 在 VS2010 上使用直接声音吗?

c# - 将方法添加到字典以供用户选择

java - 数组作为 switch 语句的选项

java - 为什么我输入2时打印的是case 2?

Android:更改默认家庭应用程序

audio - 如何使用罗技键盘创建热键来更改默认声音设备?