理解 C# 中的 Switch 语句失败
在 C# 中,switch 语句允许根据给定变量的值来引导程序流程。然而,传统的 if/else 结构缺乏像 switch 语句那样“穿透”不同情况的能力。
考虑以下示例,它尝试将数字转换为其单词表示形式:
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; }
编译此代码时,它会失败并显示错误,指示控制无法从一种情况转移到另一种情况。此问题源于以下事实:在 C# 中,switch 语句需要在每个 case 之后显式中断,以确保控制执行流程。
实现 Fallthrough
To在 switch 语句中实现fallthrough,有以下三个选项:
Fallthrough 示例
以下 NumberToWords 函数的修改版本使用 goto case 语法来实现 Fallthrough:
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]); goto case 2; 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]); goto case 1; case 1: int o = number % 10; ans += numbers[o]; break; default: throw new ArgumentException("number"); } return ans; }
以上是如何在 C# 的 Switch 语句中实现 Fallthrough 行为?的详细内容。更多信息请关注PHP中文网其他相关文章!