C# 判断

`if`/`else`、`switch` 语句、`switch` 表达式与模式匹配。

Beginner
Key Points`switch` 表达式(C# 8+)能直接返回值,比语句版简洁得多。

if / else

C#
int score = 85;

if (score >= 90)
{
    Console.WriteLine("优秀");
}
else if (score >= 60)
{
    Console.WriteLine("及格");
}
else
{
    Console.WriteLine("不及格");
}
Output
及格

Conditions must be bool; C# rejects if (1) (unlike C/C++), which prevents the classic = versus == bug.

switch 语句

C#
int day = 3;

switch (day)
{
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        Console.WriteLine("工作日");
        break;
    case 6:
    case 7:
        Console.WriteLine("周末");
        break;
    default:
        Console.WriteLine("非法");
        break;
}
Output
工作日

C# forbids fall-through: every case must end with break, return or goto. To combine cases, stack multiple labels.

switch 表达式

C#
int day = 6;

string type = day switch
{
    1 or 2 or 3 or 4 or 5 => "工作日",
    6 or 7 => "周末",
    _ => "非法"
};

Console.WriteLine(type);

// 带条件的模式(when)
int score = 85;
string grade = score switch
{
    >= 90 => "A",
    >= 80 => "B",
    >= 60 => "C",
    _ => "D"
};
Console.WriteLine(grade);
Output
周末
B

The switch expression uses => and _ instead of case/default and returns a value directly. Being an expression, it fits inside var x = ....

模式匹配

C#
object[] items = { 42, "hello", 3.14, true, null! };

foreach (var item in items)
{
    string desc = item switch
    {
        int n when n > 100 => $"大整数 {n}",
        int n => $"整数 {n}",
        string s => $"字符串长度 {s.Length}",
        double d => $"浮点 {d:F2}",
        bool b => $"布尔 {b}",
        null => "null",
        _ => "其他"
    };
    Console.WriteLine(desc);
}
Output
整数 42
字符串长度 5
浮点 3.14
布尔 True
null
PatternExampleMeaning
类型模式int n是 int 并取出
常量模式0 "abc" null等于该常量
关系模式>= 90比较
逻辑模式and or not组合
属性模式{ Length: > 3 }按属性匹配
位置模式(0, 0)解构元组/记录
列表模式[1, .., 9]匹配数组首尾
C#
int[] arr = { 1, 2, 3, 4, 5 };

string shape = arr switch
{
    [] => "空",
    [var only] => $"单个 {only}",
    [var first, .., var last] => $"首 {first} 尾 {last}",
    _ => "其他"
};
Console.WriteLine(shape);
Output
首 1 尾 5
A switch expression must be exhaustive or the compiler warns (CS8509). A _ => ... arm silences it; omit _ when you want to be told about missing cases.

Friends & Partners