当前位置: 首页 > web >正文

C#学习第30天: 匹配模式

模式匹配(Pattern Matching)是 C# 中一个强大且灵活的特性,允许开发者以更直观的方式检查数据结构,并根据特定模式执行操作。

随着 C# 语言版本的发展,模式匹配的功能越来越丰富,为处理复杂数据提供了极大的便利。

本文将深入介绍 C# 中的模式匹配,并提供各种使用场景的示例。

目录

1. 类型模式

2.常量模式

3.属性模式

4.位置模式

 5.组合模式

6. when 子句

7. switch 表达式

8.递归模式


1. 类型模式

说明

类型模式用于检查一个对象是否是某个特定的类型。如果匹配成功,可以直接将对象解构为该类型的变量。

示例

object data = 42;if (data is int number)
{Console.WriteLine($"The number is {number}.");
}object text = "Hello, C#";if (text is string message)
{Console.WriteLine($"Message length: {message.Length}");
}

2.常量模式

说明

常量模式用于检查对象的值是否与某个常量相等,通常在 switch 语句中使用。

示例

string command = "start";switch (command)
{case "start":Console.WriteLine("Starting...");break;case "stop":Console.WriteLine("Stopping...");break;default:Console.WriteLine("Unknown command");break;
}

3.属性模式

说明

属性模式用来检查对象的属性是否满足某些条件。它使用冒号 : 来分隔属性名称和匹配条件。

示例

public class Rectangle
{public int Width { get; set; }public int Height { get; set; }
}Rectangle rect = new Rectangle { Width = 10, Height = 5 };if (rect is { Width: > 5, Height: < 10 })
{Console.WriteLine("Rectangle is within the desired dimensions.");
}

4.位置模式

说明

位置模式适用于元组和记录类型,允许通过解构检查对象的元素。

示例

var point = (X: 10, Y: 20);if (point is (10, 20))
{Console.WriteLine("Point is at the expected location.");
}public record Circle(int Radius, (int X, int Y) Center);Circle circle = new Circle(5, (0, 0));if (circle is Circle(5, (0, 0)))
{Console.WriteLine("Circle is at the origin with radius 5.");
}

 5.组合模式

说明

组合模式允许使用逻辑运算符将多个模式组合在一起,形成更复杂的匹配条件。

示例

object item = 25;if (item is int i && i > 10)
{Console.WriteLine("The integer is greater than 10.");
}string input = "example";if (input is not null && input.Length > 5)
{Console.WriteLine("The input string is longer than 5 characters.");
}

6. when 子句

说明

when 子句允许在模式匹配中添加额外的条件判断。它可以与 switch 语句结合使用。

示例

int score = 85;switch (score)
{case int n when n >= 90:Console.WriteLine("Grade: A");break;case int n when n >= 80:Console.WriteLine("Grade: B");break;default:Console.WriteLine("Below B");break;
}

7. switch 表达式

说明

switch 表达式引入了一种简洁的语法来表达基于模式的分支。

示例

string status = "running";string message = status switch
{"running" => "The system is running.","stopped" => "The system has stopped.",_ => "Unknown status."
};Console.WriteLine(message);

8.递归模式

说明

递归模式允许对嵌套的数据结构进行深层次的模式匹配。

示例

public record TreeNode(string Name, TreeNode? Left, TreeNode? Right);var root = new TreeNode("Root", new TreeNode("Left", null, null), new TreeNode("Right", null, null));if (root is TreeNode("Root", TreeNode("Left", null, null), TreeNode("Right", null, null)))
{Console.WriteLine("Matched the entire tree structure.");
}

不同类型的模式匹配适用于不同的场景,可以显著提高代码的可读性和维护性。希望本文能帮助你更好地理解和应用 C# 中的模式匹配特性。如果你有任何疑问或需要进一步的帮助,请随时留言交流!

http://www.xdnf.cn/news/13754.html

相关文章:

  • 大模型技术30讲-5-利用数据来减少过拟合现象
  • Next.js + Supabase = 快速开发 = 高速公路
  • 怎样下载某个SCI期刊的endnote style?答:直接去endnote官网搜索期刊名称并下载即可
  • JMeter + 命令行服务器端压测全流程详解
  • 风控系统中,要调用第三方服务获取信息,很慢,如何解决?
  • vue3项目移动端实现进度条可手动滑动控制进度和点击控制进度
  • Docker入门篇--从安装到使用
  • 【Linux手册】从「程序」到「进程」:计算机世界的运行机制
  • 智慧养老与数字健康:科技赋能老年生活,构建全方位养老体系
  • Redis核心数据结构详解与应用
  • arduino通过控制器,精准控制24V电动轮毂转动
  • 解锁Scrapy爬虫:从入门到实战的Python秘籍
  • 图像分割技术:像素级的精准识别(superior哥深度学习系列第12期)
  • 关于MySql深分页的问题及优化方案
  • 软件测试的艺术与科学:构建商业级产品的优雅草卓伊凡
  • 微信小程序渗透测试指北(附案例)
  • ATM 模拟器 Golang 程序--示例
  • 【二分答案1-----切木棒】
  • 基于YOLOv11与单目测距的实战教程:从目标检测到距离估算
  • 嵌入式通信模块实战新范式:基于虚拟仿真平台的NB-IoT核心技能训练——零硬件损耗的全栈式实验方案,重构物联网通信教学逻辑
  • 基于多面体模型的编译优化技术
  • Ubuntu 绑定Conda
  • 在 Vue 3 中修改 el-select 组件接收的 prop 值
  • Parasoft C++Test软件集成测试(部件测试)_操作指南
  • 【3D插件推荐】PolyCloth v2.07 超强布料模拟工具(附图文安装教程与下载)
  • 力扣面试150题--单词接龙
  • stm32cubeide中编译非flash起始地址开始的程序
  • 解决vscode中使用debuger运行app.py但是报错No module named app的方法
  • kali2024 由于没有公钥,无法验证下列签名---解决方案
  • docker compose搭建elk 8.6.2