C# 匹配模式

在C#中,匹配模式通常指的是使用模式匹配(Pattern Matching)功能来检查一个对象是否符合特定的结构,并从中提取所需的信息。C# 7.0及更高版本引入了几个新的特性来支持模式匹配,主要包括:

  1. switch表达式

  2. is表达式

  3. when子句

  4. 属性模式

  5. 元组模式

  6. var模式

  7. 常量模式

  8. 声明模式

  9. 递归模式

  10. 关系模式

1. 使用is表达式进行类型检查和模式匹配

is表达式可以用来检查一个对象是否为特定类型,并同时将该对象转换为该类型。

复制代码
复制代码

object obj = "Hello, World!";

if (obj is string text)

{

Console.WriteLine(text.ToUpper()); // 输出: HELLO, WORLD!

}

else

{

Console.WriteLine("Not a string");

}

2. 使用switch表达式进行模式匹配

C# 7.0引入了switch表达式,使得在switch语句中可以使用模式匹配。

复制代码
复制代码

object obj = "Hello, World!";

switch (obj)

{

case string s when s.StartsWith("Hello"):

Console.WriteLine($"Starts with 'Hello': {s}");

break;

case int i:

Console.WriteLine($"It's an integer: {i}");

break;

default:

Console.WriteLine("Not matched");

break;

}

3. 元组模式匹配

元组模式匹配允许你检查元组中的元素。

复制代码
复制代码

(int, string) tuple = (1, "Hello");

if (tuple is (int id, string message) && id > 0)

{

Console.WriteLine($"ID: {id}, Message: {message}");

}

4. 属性模式匹配(C# 8.0及以后)

属性模式允许你直接匹配对象的属性值。

复制代码
复制代码

public class Person

{

public string Name { get; set; }

public int Age { get; set; }

}

Person person = new Person { Name = "Alice", Age = 30 };

if (person is { Name: "Alice", Age: > 25 })

{

Console.WriteLine("Name is Alice and Age is greater than 25.");

}

5. 递归模式(C# 8.0及以后)

递归模式允许你在嵌套结构中使用模式匹配。例如,匹配一个树结构。

复制代码
复制代码

record Tree(string Value, Tree? Left, Tree? Right);

var tree = new Tree("Root", new Tree("Left", null, null), new Tree("Right", null, null));

if (tree is { Left: { Value: "Left" }, Right: { Value: "Right" } })

{

Console.WriteLine("Tree matches the pattern.");

}

通过这些特性,C#的模式匹配功能非常强大,可以用于多种场景,包括但不限于类型检查、数据提取和条件逻辑处理。

相关推荐
小码编匠12 小时前
WPF 中的高级交互通过右键拖动实现图像灵活缩放
后端·c#·.net
唐青枫19 小时前
C#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez20101 天前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools2 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫2 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下3 天前
最终的信号类
开发语言·c++·算法
echoarts3 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix3 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz3 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式