C#: Workaround for Illegal Switch Statement?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Switch statement fallthrough in C#?
以下代码在C中是非法的,因为控件不能从一个case标签落到另一个case标签上。然而,这种行为在C++中是完全合法的。那么,如何在C中对相同的行为进行编码呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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; } |
埃里克·利珀特是这门语言的研究者,他在这里谈到这门语言:http://ericlippert.com/2009/08/13/four-switch-oddities/
短版本:最简单的解决方法是使用goto:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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和显式分支有助于防止编写bug,并向未来的维护人员清楚地表明,这是有意的。
考虑到这是一个数字枚举,并且在所有情况下基本上都执行相同的操作,您可以将其重新编写为循环:
1 2 3 4 5 6 7 8 9 10 11 | 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语句的通用答案,但对于本例来说,这是相当不错的。