模式匹配(Pattern Matching) 是 C# 中一种强大的语言特性,它允许你 根据数据的“形状”(类型、值、结构)来有条件地执行代码,而不仅仅是传统的 if-else 或 switch 判断。

✅ 简单说:“看一个对象长什么样,然后决定怎么处理它。”


🎯 为什么需要模式匹配?

传统写法往往冗长、易错:

// 老式写法:先 is 判断,再强制转换
if (obj is string)
{
    string s = (string)obj;
    Console.WriteLine(s.ToUpper());
}
else if (obj is int)
{
    int i = (int)obj;
    Console.WriteLine(i * 2);
}

模式匹配让代码更简洁、安全、表达力更强!


🔍 C# 模式匹配的演进

C# 版本新增模式
C# 7.0类型模式、常量模式、var 模式、is 表达式
C# 8.0switch 表达式、属性模式、元组模式、弃元模式
C# 9.0+关系模式(<, >)、逻辑模式(and/or/not)
C# 10+扩展属性模式、列表模式([..])

✅ 常见模式类型 + 示例(C# 8.0+ 推荐写法)

1️⃣ 类型模式(Type Pattern)

检查类型并同时声明变量(避免重复转换)

if (shape is Circle c)
{
    Console.WriteLine($"半径: {c.Radius}");
}
else if (shape is Rectangle r)
{
    Console.WriteLine($"面积: {r.Width * r.Height}");
}

2️⃣ 属性模式(Property Pattern)

根据对象的属性值进行匹配

public record Person(string Name, int Age);

var p = new Person("Alice", 30);

// 匹配特定属性值
if (p is { Name: "Alice", Age: 30 })
{
    Console.WriteLine("找到 Alice!");
}

// 部分匹配 + 声明变量
if (p is { Age: > 18 } adult)
{
    Console.WriteLine($"{adult.Name} 是成年人");
}

3️⃣ switch 表达式(C# 8.0)

比传统 switch 更简洁、函数式

static string GetWeatherMessage(int temperature) =>
    temperature switch
    {
        < 0 => "天寒地冻",
        >= 0 and < 15 => "有点冷",
        >= 15 and <= 25 => "舒适宜人",
        > 25 => "炎热",
        _ => "未知温度" // 弃元模式(相当于 default)
    };

4️⃣ 关系模式 + 逻辑模式(C# 9.0)

直接使用 <, >, and, or, not

if (score is >= 90 and <= 100)
    grade = "A";
else if (score is >= 80)
    grade = "B";
else if (score is < 60 or > 100)
    grade = "无效";

5️⃣ 列表模式(C# 11+)

匹配数组或列表的结构

int[] numbers = { 1, 2, 3, 4, 5 };

if (numbers is [1, 2, .. var rest]) // 开头是 1,2,其余存入 rest
{
    Console.WriteLine($"剩余元素: {string.Join(", ", rest)}"); // 3, 4, 5
}

// 检查是否为空
if (list is [])
    Console.WriteLine("空列表");

// 检查只有一个元素
if (list is [var single])
    Console.WriteLine($"唯一元素: {single}");

6️⃣ 弃元模式(Discard Pattern)

用 _ 忽略不需要的值

// 只关心是否有值,不关心具体值
if (result is { Success: true, Data: _ })
{
    Console.WriteLine("操作成功");
}

🆚 传统写法 vs 模式匹配

❌ 传统:冗长、易出错

if (obj != null && obj is Customer)
{
    var c = (Customer)obj;
    if (c.Age >= 18 && c.City == "Beijing")
    {
        // ...
    }
}

✅ 模式匹配:清晰、安全、一行搞定

if (obj is Customer { Age: >= 18, City: "Beijing" } c)
{
    // 直接使用 c
}

💡 真实应用场景

场景模式匹配写法
API 返回结果处理if (response is { IsSuccess: true, Data: var data })
状态机state switch { "Init" => ..., "Running" => ... }
树形结构遍历node is BinaryTreeNode { Left: not null, Right: null }
配置验证config is { Port: > 0 and < 65536, Host: not null }

⚠️ 注意事项

  1. 性能:模式匹配在编译后通常转为高效 IL,性能与手写 if 相当。
  2. 可读性:避免过度嵌套复杂模式,保持代码清晰。
  3. null 安全:is 模式自动处理 null(null is T 永远为 false)。

✅ 总结

模式类型用途
类型模式obj is Type var
属性模式obj is { Prop: value }
关系/逻辑模式x is > 0 and < 100
列表模式list is [1, 2, ..]
弃元模式.. 或 _ 忽略部分

🧠 记住:
“模式匹配 = 解构 + 条件判断 + 变量声明”三位一体。

它让 C# 从“面向对象”走向“面向数据”,是现代 C# 最优雅、最强大的特性之一。
如果你还在写一堆 if (x is T) { var y = (T)x; ... },是时候升级到模式匹配了!😊

在实际使用中,可以将发送给plc的数据,在发送前做一个模式匹配,例如将float转化成uint类型。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐