是否有可能在C#7.0中重载解构器?

时间:2017-01-30 09:35:28

标签: c# visual-studio-2017 c#-7.0

在C#7.0中,我可以为我的班级声明以下解构器:

public class Customer
{
    public string FirstName { get; }
    public string LastName { get; }
    public string Email { get; }

    public Customer(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }

    public void Deconstructor(out string firstName, out string lastName, out string company)
    {
        firstName = FirstName;
        lastName = LastName;
        company = "Nop-Templates";
    }

    public void Deconstructor(out string firstName, out string lastName)
    {
        firstName = FirstName;
        lastName = LastName;
    }
}

我认为在析构函数中使用变量而不是直接返回元组的想法是这样的,你可以对解构函数进行不同的重载。但是,我似乎无法将对象解构为三个变量。我只能将它解构为两个变量。

例如,这不会编译:

(string firstName, string lastName, string company) = customer;

我收到了这个错误:

"无法解构' 2'元素进入' 3'变量"

但这确实有效:

(string firstName, string lastName) = customer;

我错过了什么?

1 个答案:

答案 0 :(得分:3)

您调用了方法Deconstructor,而不是Deconstruct。此外,您无法在两个元组中重新声明firstNamelastName。进行这些更改,以下几行代码都编译得很好:

var customer = new Customer("a", "b");
(string firstName1, string lastName1, string company) = customer;
(string firstName2, string lastName2) = customer;