控制流程陳述式是程式設計的基石。C# 提供 if、switch 兩大選擇陳述式,以及 for、while、do-while、foreach 等迴圈結構。本章重點解析與 C/C++ 的關鍵差異,避免常見錯誤。
C# if 條件必須為 bool 型別,不允許整數或物件隱性轉換。常見錯誤修正:
| 錯誤寫法 (C/C++ 風格) | 正確寫法 (C#) |
|---|---|
if (str.Length) | if (str.Length != 0) |
if (n = 5) | if (n == 5) |
比較運算子:==、!=、<、<=、>、>=。邏輯運算子 &&(AND)、||(OR)具短路特性,建議將最可能短路的運算式置前以提升效能。
C# switch 不允許 case 之間隱性貫穿,每個 case 區塊必須以 break、return、throw 或 goto case label/goto default 結束。這消除了 C/C++ 常見的漏寫 break 導致的難發現 Bug。
支援型別:sbyte, byte, short, ushort, int, uint, long, ulong, char, string, enum。字串可直接作為 case 標籤,這是 C/C++ 不支援的特性。
switch (command) {
case "START": StartService(); break;
case "STOP": StopService(); break;
default: LogUnknownCommand(command); break;
}
標準三段式:for (init; condition; increment)。變數可在初始化區塊宣告,作用域限於迴圈內。
while (condition) { ... }:先判斷後執行。do { ... } while (condition);:至少執行一次。專為實作 IEnumerable 的集合設計,語法簡潔且唯讀(迴圈變數不可修改):
foreach (string name in names) {
Console.WriteLine(name);
}
break:離開最近的迴圈或 switch。continue:跳過本次迴圈剩餘部分,直接進入下一次迭代。goto:跳轉至標籤,慎用。可用於 switch 的 goto case/goto default。return:離開方法並回傳值。throw:拋出例外。
public static int Main(string[] args) {
if (args.Length != 1) {
Console.WriteLine("Usage: one argument");
return 1;
}
char ch = args[0][0];
if (ch >= 'A' && ch <= 'Z')
Console.WriteLine("{0} is uppercase", ch);
else if (ch >= 'a' && ch <= 'z')
Console.WriteLine("{0} is lowercase", ch);
else if (Char.IsDigit(ch))
Console.WriteLine("{0} is a digit", ch);
return 0;
}
C# 控制流程陳述式在保留 C/C++ 熟悉語法的同時,強制型別安全(布林條件)、禁止隱性貫穿、支援字串 switch,並提供 foreach 簡化集合遍歷。掌握這些差異能寫出更健壯、可維護的程式碼。