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

在 C# 中,位置模式(Positional Pattern)通过解构方法来提取对象的多个值,并在模式匹配中进行判断或赋值。它依赖于类型的 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;
}}
一旦定义了 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 中。
位置模式还支持嵌套。只要被嵌套的类型也实现了 Deconstruct,就可以逐层拆解。
例如,有一个包含 Address 的 Employee 类:
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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号