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

月夜之吻
发布: 2025-09-27 09:48:01
原创
1011人浏览过
位置模式通过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; }
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">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" };
<p>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 中。

北极象沉浸式AI翻译
北极象沉浸式AI翻译

免费的北极象沉浸式AI翻译 - 带您走进沉浸式AI的双语对照体验

北极象沉浸式AI翻译 0
查看详情 北极象沉浸式AI翻译

支持嵌套解构

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

例如,有一个包含 AddressEmployee 类:

public class Address
{
    public string City { get; set; }
    public string Country { get; set; }
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">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" } 
};
<p>if (emp is ("Tom", ("Beijing", "China")))
{
Console.WriteLine("Employee Tom lives in Beijing, China.");
}
登录后复制

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

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

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

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号