第 3 課 · 約 12 分鐘 · ← 第 2 課

做決策:if、else、switch

程式開始有意思,是從它會反應開始的。C# 的選擇只有三種形狀——鏈、表、單行——外加一條黃金法則:條件永遠是 bool。

if:問一個是非題

int temperature = 22;

if (temperature > 30)
{
    Console.WriteLine("too hot");     // 不會執行:22 不大於 30
}
else
{
    Console.WriteLine("temperature is fine");
}

else if:一串檢查點

鏈從上往下跑,在第一個成立的條件處停住——順序就是邏輯:

int score = 85;

if (score >= 90)
{
    Console.WriteLine("A");
}
else if (score >= 80)      // 只有 score >= 90 為假才會到這裡
{
    Console.WriteLine("B");
}
else if (score >= 70)
{
    Console.WriteLine("C");
}
else
{
    Console.WriteLine("F");
}

組合問題:&& 和 ||

&& = "並且"(兩邊都得成立)。|| = "或者"(至少一邊)。! = "非"。它們都短路:答案一確定,剩下的連算都不算。

int day = 6;          // 週六
bool holiday = false;

if (day == 6 || day == 7)
{
    Console.WriteLine("weekend, enjoy!");
}

if (day == 6 && !holiday)     // && 要求兩邊都為真
{
    Console.WriteLine("personal project time");
}
else
{
    Console.WriteLine("not a holiday");
}

黃金法則:條件是 bool,別的都不是

從 C、C++ 或 JavaScript 過來的?這個坑人人踩:if (1) 在 C# 裡是編譯錯誤。數字不是真值:

int count = 3;
if (count)   // error CS0029: 無法將型別"int"隱式轉換為"bool"
{
    Console.WriteLine("three");
}
int count = 3;
if (count == 3)   // 把意思說清楚:比較式才會產出 bool
{
    Console.WriteLine("three");
}

switch:一個值,多個精確匹配

拿同一個表示式對比很多常量時,switch 比 else if 鏈乾淨:

string order = "espresso";

switch (order)
{
    case "espresso":
        Console.WriteLine("espresso — small and strong");
        break;
    case "latte":
    case "cappuccino":              // 疊式標籤:兩種單,一個配方
        Console.WriteLine("milky and large");
        break;
    default:
        Console.WriteLine("unknown order");
        break;
}

C# switch 的一條鐵律:每個非空 case 必須以 break;、return; 或 throw; 結尾。忘了就是 CS0163——C# 拒絕那個坑害了無數 C 程式的"貫穿"。

三元:塞進一個表示式裡的 if

int age = 20;
string status = age >= 18 ? "adult" : "minor";   // 條件 ? 真值 : 假值
Console.WriteLine(status);
Console.WriteLine(15 >= 18 ? "adult" : "minor");

兩個分支都產出值時用它。當你想在三元里再套三元——寫真正的 if,未來的你會感謝現在的你。

現在就練