切换声明在C#中落后?
切换声明是我喜爱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应该在函数之外声明:嗯,他们是,这只是一个例子。
编译器失败并出现以下错误:
控制不能从一个案例标签('案例3:')落到另一个案例标签 控制不能从一个案例标签('案例2:')落到另一个案例标签
为什么?有没有办法在没有三个if
s的情况下获得这种行为?
牛魔王的故事
梵蒂冈之花
相关分类