掌握條件判斷、迴圈與跳躍陳述式是撰寫高品質 C# 程式的基礎。本文整理所有核心語法並附上 switch 字串比較的實務技巧。
// 條件判斷
if (bool) { } else { }
switch (v)
{
case v1: ... break;
case v2: ... break;
default: ... break;
}
// 迴圈
do { } while (bool);
while (bool) { }
for (int i = 0; i < 10; i++) { }
foreach (Type item in items) { }
// 跳躍
break;
continue;
goto Label; // 需搭配標籤使用
C# 的 switch 原生支援字串,但 case 標籤必須為編譯期常數(const string),不可使用變數。
using System;
class MyClass
{
static void Main()
{
string[] str = { "a", "bb", "ccc" };
// 必須使用 const string
const string s1 = "bb";
const string s2 = "ccc";
foreach (string s in str)
{
switch (s)
{
case s1: Console.WriteLine(s.Length); break; // 輸出 2
case s2: Console.WriteLine(s.Length); break; // 輸出 3
default: Console.WriteLine(s); break; // 輸出 "a"
}
}
Console.ReadKey();
}
}
switch 的 case 必須為 const,C# 7.0+ 可使用 pattern matching 擴展功能(如 case int n when n > 0:)。