理解 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,有以下三個選項:
goto default 語法將控制轉移到預設情況,即使目前大小寫不等於預設大小寫。
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中文網其他相關文章!