gpt4 book ai didi

C# - 构造函数的链式调用

转载 作者:行者123 更新时间:2023-11-30 13:12:23 24 4
gpt4 key购买 nike

我目前正在学习 C#,我正在学习构造函数和构造函数的链式调用,以便不必在每个构造函数中粘贴相同的代码(变量的值相同)。

我有三个构造函数,一个没有参数,一个有三个参数,一个有四个参数。我想要做的是,使用默认构造函数调用具有三个参数的构造函数,传递参数(变量)的默认值和具有三个参数的构造函数,我正在寻找用四个参数调用构造函数参数。我似乎已经对第一个列表的默认值进行了排序,但我正在努力如何编写具有三个参数的构造函数,然后在需要时使用四个参数调用构造函数。

默认构造函数应将所有字符串类型的实例变量分配给string.Empty。

public Address()
{
m_street = string.Empty;
m_city = string.Empty;
m_zipCode = string.Empty;
m_strErrMessage = string.Empty;
m_country = Countries;
}


public Address(string street, string city, string zip)
{
}

public Address(string street, string city, string zip, Countries country)
{
}

我想执行以下操作,但它不起作用:-

public Address(string street, string city, string zip)
: this street, string.Empty, city, string.Empty, zip, string.Empty
{
}

最佳答案

您通常应该将具有最少 信息的构造函数链接到具有最多 信息的构造函数,而不是相反。这样每个字段都可以精确地分配到一个地方:具有最多信息的构造函数。实际上,您已经在帖子中描述了这种行为 - 但您的代码做了完全不同的事情。

您还需要使用正确的构造函数链接语法,即:

: this(arguments)

例如:

public class Address
{
private string m_street;
private string m_city;
private string m_zipCode;
private string m_country;

public Address() : this("", "", "")
{
}


public Address(string street, string city, string zip)
: this(street, city, zip, "")
{
}

public Address(string street, string city, string zip, string country)
{
m_street = street;
m_city = city;
m_zip = zip;
m_country = country;
}
}

有关构造函数链接的更多信息,请参阅 this article我之前写过。

关于C# - 构造函数的链式调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6944729/

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