C# 中的模式匹配位置模式如何解构对象?

位置模式通过Deconstruct方法解构对象,支持在switch和is表达式中进行值匹配与提取,如Person类拆解姓名、Employee嵌套Address实现多层匹配,提升代码可读性

c# 中的模式匹配位置模式如何解构对象?

在 C# 中,位置模式(Positional Pattern)通过解构方法来提取对象的多个值,并在模式匹配中进行判断或赋值。它依赖于类型的 Deconstruct 方法,将对象“拆开”成若干部分,再与模式中的参数逐一匹配。

Deconstruct 方法是关键

要使用位置模式,类型必须提供一个或多个 Deconstruct 实例或扩展方法,用于返回多个值。该方法使用 out 参数输出解构后的值。

例如:

定义一个 Person 类并添加 Deconstruct 方法:

public class Person{    public string FirstName { get; set; }    public string LastName { get; set; }
public void Deconstruct(out string firstName, out string lastName){    firstName = FirstName;    lastName = LastName;}

}

在 switch 表达式或 is 表达式中使用位置模式

一旦定义了 Deconstruct 方法,就可以在模式匹配中使用元组语法来匹配对象的组成部分。

示例:使用 switch 表达式

Person person = new Person { FirstName = "John", LastName = "Doe" };

string result = person switch{("John", "Doe") => "Found John Doe",(var first, "Smith") => $"First name is {first}, last name is Smith",_ => "Unknown person"};

这里,("John", "Doe") 就是位置模式,C# 自动调用 Deconstruct 方法,把 person 拆成两个字符串,并与字面量比较。

示例:使用 is 表达式提取值

if (person is ("Alice", var lastName)){    Console.WriteLine($"Hello Alice, your last name is {lastName}");}

如果 FirstName 是 "Alice",则匹配成功,并将 LastName 提取到变量 lastName 中。

支持嵌套解构

位置模式还支持嵌套。只要被嵌套的类型也实现了 Deconstruct,就可以逐层拆解。

例如,有一个包含 AddressEmployee 类:

public class Address{    public string City { get; set; }    public string Country { get; set; }
public void Deconstruct(out string city, out string country){    city = City;    country = Country;}

}

public class Employee{public string Name { get; set; }public Address HomeAddress { get; set; }

public void Deconstruct(out string name, out Address address){    name = Name;    address = HomeAddress;}

}

可以这样写嵌套模式:

Employee emp = new Employee {     Name = "Tom",     HomeAddress = new Address { City = "Beijing", Country = "China" } };

if (emp is ("Tom", ("Beijing", "China"))){Console.WriteLine("Employee Tom lives in Beijing, China.");}

这会依次解构 Employee 和其内部的 Address

基本上就这些。位置模式让对象结构可以直接参与逻辑判断,代码更简洁清晰。

以上就是C# 中的模式匹配位置模式如何解构对象?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1440049.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月17日 16:42:12
下一篇 2025年12月17日 16:42:23

相关推荐

发表回复

登录后才能评论
关注微信