首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 控制流程語句完整指南:選擇與迴圈結構詳細解析

     編輯:關於C語言

前言

控制流程是程式邏輯骨架。C# 提供 if/switch 選擇結構,以及 for/foreach/while/do-while 四種迴圈,本文詳細解析語法、陷阱與最佳實務。

一、選擇語句

1. if 語句


if (boolExpr) statement;
if (boolExpr) statement1 else statement2;

關鍵規則:條件必須為 bool


// C/C++ 慣用寫法 (錯誤)
if (str.Length) { } // CS0029: 無法隱含轉換 int 到 bool

// C# 正確寫法
if (str.Length != 0) { }
if (str.Length > 0) { }

避免賦值誤判


// C/C++ 易犯錯
if (x = 5) { } // 永真,C# 編譯錯誤

// C# 強制比較
if (x == 5) { }

短路邏輯運算子

  • &&:左側 false → 右側不執行
  • ||:左側 true → 右側不執行

// 危險:短路導致賦值不執行
if (true || (len = str.Length) > 0) { } // len 未賦值
// 建議:勿在條件式中執行有副作用的運算

2. switch 語句

語法


switch (expr)
{
    case const1: stmts; break;
    case const2:
    case const3: stmts; break; // 群組 case
    default: stmts; break;
}

支援型別

sbyte, byte, short, ushort, int, uint, long, ulong, char, string, enum 及可隱含轉換者。

禁止貫穿:必須明確跳轉


// C# 錯誤:不允許隱含 fall-through
switch (n) { case 1: Do(); case 2: DoMore(); }

// 正確:明確 break 或 goto
switch (n)
{
    case 1: Do(); break;
    case 2: DoMore(); break;
}

// 需要合併邏輯:使用 goto case
switch (n)
{
    case 2: goto case 3; // 明確跳轉
    case 3: Handle2And3(); break;
    case 4: goto default;
    default: HandleOther(); break;
}

字串 switch (C# 亮點)


string name = "Chris";
switch (name)
{
    case "Chris": Console.WriteLine("Hello Chris!"); break;
    case "Admin": Console.WriteLine("Hello Admin!"); break;
}

二、迴圈語句

1. for 迴圈


for (init; condition; iterator) statement;
// 三段式皆可省略
for (;;) { if (done) break; } // 無限迴圈

多變數初始化/迭代


for (int i = 0, j = 10; i < j; i++, j--) { ... }

階乘範例


long fact = 1;
for (long i = 1; i <= n; i++) fact *= i;

break / continue

  • break:離開迴圈
  • continue:跳過本次迭代,直接執行 iterator

2. foreach 迴圈

語法


foreach (Type item in collection) statement;

需求:集合實作 IEnumerable/GetEnumerator

  • 傳回型別需有 MoveNext() 與 Current 屬性
  • 陣列、List<T>、Dictionary<TKey,TValue> 皆支援

限制

  • 迴圈變數 唯讀,不可指派、不可 ref/out 傳遞
  • 型別錯誤編譯通過,執行期拋 InvalidCastException

環境變數列舉範例


IDictionary env = Environment.GetEnvironmentVariables();
foreach (string key in env.Keys)
    Console.WriteLine($"{key} = {env[key]}");

3. while 迴圈


while (condition) statement;
// 條件為 bool,0 次或多次執行

讀取檔案範例


using (var sr = File.OpenText("file.cs"))
{
    string line;
    while ((line = sr.ReadLine()) != null)
        Console.WriteLine(line);
}

條件中賦值風險

同 if,短路可能導致賦值不執行,建議分行寫。

4. do-while 迴圈


do { statement; } while (condition);
// 保證至少執行一次

互動式平均值範例


double sum = 0; int count = 0; char cont = 'y';
do
{
    Console.Write("Enter value: ");
    double v = double.Parse(Console.ReadLine());
    sum += v; count++;
    Console.Write("Continue? (y/n): ");
    cont = Console.ReadLine()[0];
} while (cont == 'y');
Console.WriteLine($"Average = {sum / count}");

三、跳轉語句補充

語句用途注意
break離開 switch/迴圈僅離開最內層
continue跳過本次迴圈僅用於迴圈
goto跳轉標籤慎用,switch 中允許 goto case/goto default
return離開方法
throw拋出例外

四、最佳實務速查表

情境建議結構理由
雙向分支if-else清晰可讀
多重離散值比較switch效能優於 if 鏈,支援字串
已知迴圈次數for語意明確
列舉集合/陣列foreach簡潔、避免索引錯誤
條件未知次數while前置檢查
至少執行一次do-while後置檢查
需索引操作for / for (int i=0; iforeach 不提供索引

五、常見陷阱總結

  1. 條件非 bool:C# 嚴格要求 bool,無隱含轉換
  2. switch 隱含貫穿:必須 break/goto/return/throw 明確離開
  3. foreach 修改集合:迴圈中增刪集合元素 → InvalidOperationException
  4. foreach 唯讀變數:item = newVal 編譯錯誤
  5. 短路副作用:條件式中避免賦值/方法呼叫
  6. 無限迴圈無跳出:while(true) 確保內部有 break

總結

C# 控制流程語句在 C/C++ 基礎上強化型別安全 (bool 條件)、移除隱含貫穿、新增字串 switch 與 foreach 列舉。掌握四種迴圈適用場景、善用 break/continue 控制流向、避開短路副作用,即能撰寫清晰、健壯的流程邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved