C#开关通过错误?

时间:2012-06-18 18:03:03

标签: c#

我不知道为什么我会收到以下错误:

  

控件不能从一个案例标签('case“h”:')转到另一个案例标签(CS0163)

仅适用于H和S - 非常奇怪。

switch(myChoice)
{
    case "K":
    case "k":
        Console.WriteLine("You have chosen the Kanto region");
        break;
    case "O":
    case "o":
        Console.WriteLine("You have chosen the Orange Islands");
        break;
    case "J":
    case "j":
        Console.WriteLine("You have chosen the Johto region");
        break;
    case "H":
    case "h":
        Console.WriteLine("You have chosen the Hoenn region");
    case "S":
    case "s":
        Console.WriteLine("You have chosen the Sinoh region");
    case "U":
    case "u":
        Console.WriteLine("You have chosen the Unova region");
        break;
    case "R":
    case "r":
        Console.WriteLine("Return");
        break;
    default:
        Console.WriteLine("{0} is not a valid choice", myChoice);
        break;
}

6 个答案:

答案 0 :(得分:11)

Fallthrough仅在case语句没有正文时才有效。由于您的“h”和“s”案例中存在代码,因此您需要break

此外,作为建议:您可以在String.ToUpper()参数上执行switch,这样就可以避免检查myChoice的小写和大写变体。您的switch语句将变为:

switch(myChoice.ToUpper())
{
    case "K":
        Console.WriteLine("You have chosen the Kanto region");
        break;
    case "O":
        ...
}

答案 1 :(得分:10)

在s和h案例之后你错过了break

答案 2 :(得分:2)

答案 3 :(得分:1)

你忘记了H和S之间的中断声明。

答案 4 :(得分:1)

你错过了

break;

...声明

case "H":
case "h":
     Console.WriteLine("You have chosen the Hoenn region");
     break;
case "S":
case "s":
     Console.WriteLine("You have chosen the Sinoh region");
break;

答案 5 :(得分:1)

案例" H"添加转到案例" h" 案例" S"添加转到案例" s"

case "H":
    goto case "h";
case "h":
    Console.WriteLine("You have chosen the Hoenn region");
    break;
case "S":
    goto case "s";
case "s":
     Console.WriteLine("You have chosen the Sinoh region");
break;

是的,随着C#goto的回归!