gpt4 book ai didi

c# - 是否可以在 C# 7.0 中重载构造函数?

转载 作者:太空狗 更新时间:2023-10-29 20:33:06 25 4
gpt4 key购买 nike

在 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;

我错过了什么?

最佳答案

你调用了你的方法,Deconstructor,而不是Deconstruct。此外,您不能在两个元组中重新声明 firstNamelastName。进行这些更改,以下代码行都可以正常编译:

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

关于c# - 是否可以在 C# 7.0 中重载构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41932624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com