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

时间:2017-12-22 09:09:00

标签: c# switch-statement default break

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

以下微软文档如此说:https://docs.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):错误CS8070:控件不能从最终案例标签中切换出来('default:')

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

1 个答案:

答案 0 :(得分:3)

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阻止另一个案例后忘记添加中断。