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

来源:这里教程网 时间:2026-02-21 17:26:49 作者:

在 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;">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"
};
</p>

这里,("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; }
<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.");
}
</p>

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

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

相关推荐