2024-07-15 · C# 基础 · 学习笔记

模式匹配 pattern matching

模式匹配是 C# 7 开始引入、C# 8/9 增强的特性,让类型判断和分支更优雅。is 表达式做类型检查,switch 表达式替代传统 switch。

最实用的场景:判断对象类型并转换、根据数值或属性值分支。property pattern 可以匹配对象的属性值,relational pattern 可以比较大小。

体会:以前写一大堆 if-else 加 as 转换,现在用 switch 表达式一行搞定,可读性好很多。

代码示例

// is 类型模式
object obj = "hello";
if (obj is string s)
    Console.WriteLine($"字符串长度:{s.Length}");

// switch 表达式
string Describe(object o) => o switch
{
    0 => "零",
    int n when n > 0 => "正整数",
    int n when n < 0 => "负整数",
    null => "空",
    _ => "其他"
};

Console.WriteLine(Describe(0));      // 零
Console.WriteLine(Describe(42));     // 正整数
Console.WriteLine(Describe(-5));     // 负整数

// 属性模式
record Order(string Status, decimal Amount);
string OrderInfo(Order o) => o switch
{
    { Status: "paid", Amount: > 1000 } => "大额已支付",
    { Status: "paid" } => "已支付",
    { Status: "pending" } => "待支付",
    _ => "其他"
};
学习小结:以上是我学习这个知识点时的笔记和心得。技术学习没有捷径,多写多练多踩坑,自然就掌握了。如果这篇笔记对你有帮助,欢迎继续看看其他文章。