切换声明是我喜欢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[]
应该在函数以外声明:嗯,它们是,这只是一个例子。 this
编译器失败并出现如下错误: spa
Control cannot fall through from one case label ('case 3:') to another Control cannot fall through from one case label ('case 2:') to another
为何? 有没有办法在没有三个if
的状况下得到这种行为? 设计
他们更改了c#的switch语句(来自C / Java / C ++)行为。 我猜想的缘由是人们忘记了坠落而致使的错误。 我读过的一本书说使用goto来模拟,但这听起来不是一个很好的解决方案。 code
每一个case块后都须要一个诸如break之类的跳转语句,包括最后一个块,不管是case语句仍是default语句。 除了一个例外,(与C ++ switch语句不一样),C#不支持从一个case标签到另外一个case标签的隐式降级。 一个例外是case语句没有代码。 orm
- C#switch()文档 three
C#不支持使用switch / case语句。 不知道为何,但实际上没有它的支持。 连锁 文档
他们经过设计省略了这种行为,以免它不被意志使用但引发问题。 get
只有在案例部分中没有语句时才能使用它,例如: 编译器
switch (whatever) { case 1: case 2: case 3: boo; break; }
交换机漏洞历史上是现代软件中错误的主要来源之一。 语言设计者决定强制要求在案例结束时跳转,除非您在没有处理的状况下直接默认为下一个案例。
switch(value) { case 1:// this is still legal case 2: }