C# 中的对象解构用例 7.x

Object deconstruction use cases in C# 7.x

我刚刚一直在探索 C# 中引入的新事物 7.x。我发现 Deconstructor 函数非常有趣。

public class Person
{
    public string FistName { get; }
    public string LastName { get; }
    public int Age { get; }

    public Person(string fistName, string lastName, int age)
    {
        Age = age;
        LastName = lastName;
        FistName = fistName;
    }

    public void Deconstruct(out string fistName, out string lastName, out int age) // todo 3.0 deconstructor function
    {
        fistName = FistName;
        lastName = LastName;
        age = Age;
    }
}

...

var person = new Person("John", "Smith", 18);
var (firstName, lastName, age) = person;

Console.WriteLine(firstName);
Console.WriteLine(person.FirstName); // not much difference really

问题是,我想不出它的实际用法。 "Object" 解构在函数式编程模式匹配中非常有用。但是我相信它不能在 C# 中以这种方式使用(还?)。如果没有,是否有任何真实世界的用例?

最明显的用例是“内置”,即元组:

(int x, int y) Foo() => (1, 2);

var (a, b) = Foo();

而不是必须写:

var t = Foo();
var a = t.x;
var b = t.y;

我个人最喜欢将元组解构用于分配多个字段的表达式主体构造函数:

class Bar
{
    private readonly int _a;
    private readonly int _b;
    private readonly int _c;

    public Bar(int a, int b, int c) => (_a, _b, _c) = (a, b, c);
}

我在其他场景中使用过它们(例如将集合拆分为头部和尾部(缺点,正如在 F# 中所称),但解构元组至少对我来说仍然是最常见的用例。