在default
之后,控制应该自动从switch loop
中出来。但是C#需要使用中断语句吗?为什么在C#控件中,default
之后不自动从switch loop
中出来
下面的microsoft文档这么说: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):错误CS8070:控制不能从最终的用例标签(默认:)
但是,在取消对中断部分的注释时,代码可以正常工作。
发布于 2017-12-22 09:14:00
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()
,然后转到case 2
?避免这样的错误(忘记中断)。
您可以在default
阻止了另一种情况之后,就可以忘记添加中断。
https://stackoverflow.com/questions/47938715
复制相似问题