switchSwitch 语句失败是我个人喜欢与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:”)转移到另一个案例标签
为什么?有没有办法在没有三个 s 的情况下获得这种行为if?
if
可以通过在 a (see ) 中没有代码或switch使用特殊的(see ) 或(see ) 形式来实现通过 -s:case``case``case 0``goto case``case 1``goto default``case 2
case``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; }