第 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,未来的你会感谢现在的你。

现在就练