我刚刚探索了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问题是,我想不出它的实际用途。“对象”解构在函数式编程模式匹配中非常有用。但是,我认为它不能在C#中以这种方式使用(现在?)。如果没有,是否有任何真实的用例?
发布于 2018-04-29 08:01:03
最明显的用例是“内置”(即元组):
(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#中称为cons),但解构元组至少对我来说仍然是最常见的用例。
https://stackoverflow.com/questions/50081854
复制相似问题