C#:非法交换声明的解决方法?

时间:2010-01-07 02:38:07

标签: c# c++ switch-statement

  

可能重复:
  Switch statement fallthrough in C#?

以下代码在C#中是非法的,因为控件不能从一个案例标签转到另一个案例标签。但是,这种行为在C ++中是完全合法的。那么,你将如何在C#中编写相同的行为?

enum TotalWords
{
   One = 1,
   Two,
   Three,
   Four
}

public String SomeMethod(TotalWords totalWords)
{     
     String phrase = "";

     switch (totalWords)
     {
        case TotalWords.Four:
             phrase = "Fox" + phrase;
        case TotalWords.Three:
             phrase = "Brown" + phrase;
        case TotalWords.Two:
             phrase = "Quick" + phrase;
        case TotalWords.One:
             phrase = "The" + phrase;
             break;

        default:
             break;
     }

     return phrase;
}

2 个答案:

答案 0 :(得分:4)

负责该语言的Eric Lippert在这里谈到它:
http://ericlippert.com/2009/08/13/four-switch-oddities/

简短版本:最简单的解决方法是使用转到:

switch (totalWords)
 {
    case TotalWords.Four:
         phrase = "Fox" + phrase;
         goto case TotalWords.Three;
    case TotalWords.Three:
         phrase = "Brown" + phrase;
         goto case TotalWords.Two;
    case TotalWords.Two:
         phrase = "Quick" + phrase;
         goto case TotalWords.One;
    case TotalWords.One:
         phrase = "The" + phrase;
         break;

    default:
         break;
 }

我认为这里的理由是,10次失误中有9次是错误而不是故意。强制你使用break和一个明确的分支有助于防止你编写错误,并让未来的维护人员清楚地知道这是故意的。

答案 1 :(得分:0)

鉴于这是一个数字枚举,并且您在所有情况下都基本上执行相同的操作,您可以将其重新编写为循环:

String[] phrase_bits = new String[] { "The", "Quick", "Brown", "Fox" };

public String SomeMethod(TotalWords totalWords)
{
    int x = (int) totalWords;
    String phrase = ""
    while (--x >= 0) {
        phrase = phrase_bits[x] + phrase
    }
    return phrase
}

这不是所有switch语句的通用答案,但对于这种情况,它相当不错。