switch语句的下通是为爱我个人的一个重要原因switch与if/else if结构。这里有一个示例:
switch
if/else if
static string NumberToWords(int number) { string[] numbers = new string[] { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; string[] tens = new string[] { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; string[] teens = new string[] { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; string ans = ""; switch (number.ToString().Length) { case 3: ans += string.Format("{0} hundred and ", numbers[number / 100]); case 2: int t = (number / 10) % 10; if (t == 1) { ans += teens[number % 10]; break; } else if (t > 1) ans += string.Format("{0}-", tens[t]); case 1: int o = number % 10; ans += numbers[o]; break; default: throw new ArgumentException("number"); } return ans; }
聪明人之所以屈服,是因为string[]s应该在函数外部声明:好的,这只是一个例子。
string[]
编译器失败,并出现以下错误:
控件不能从一个案例标签(“案例3:”)落入另一个案例标签 控件不能从一个案例标签(“案例2:”)落入另一个案例标签
为什么?还有没有三秒就可以得到这种行为的任何方法if吗?
if
(复制/粘贴我在其他地方提供的答案)
通过下降switch- caseS可通过不具有代码在一个来实现case(见case 0),或者使用特殊的goto case(见case 1)或goto default(见case 2)形式:
case
case 0
goto case
case 1
goto default
case 2
switch (/*...*/) { case 0: // shares the exact same code as case 1 case 1: // do something goto case 2; case 2: // do something else goto default; default: // do something entirely different break; }