C# – 构造函数的链调用

我正在学习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 { } 

我们的想法是将实例化的逻辑留给构造函数,该构造函数接受大多数参数,并将其他参数作为仅将值传递给该构造函数的方法,这样您只需编写一次代码。

试试这个:

 public Address() : this(String.Empty, String.Empty, String.Empty) { } public Address(string street, string city, string zip) : this(street, city, zip, null) { } public Address(string street, string city, string zip, Countries country) { m_street = street; m_city = city; m_zipCode = zip; m_country = Countries; m_strErrMessage = string.Empty; } 

您通常应该将具有最少信息的构造函数链接到具有最多信息的构造函数,而不是反过来。 这样,每个字段只能在一个地方分配:具有最多信息的构造函数。 你实际上已经在post中描述了这种行为 – 但是你的代码完全不同。

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

 : 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; } } 

有关构造函数链接的更多信息,请参阅我刚才写的这篇文章 。

你需要 ():

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

这将调用Address constuctor指定6个args中的3个(如果有的话),那是你想要做的吗?

你的语法很接近。 试试这个

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

在您的示例中,您还应该删除默认构造函数,并将变量的初始化放入链末尾的构造函数中。 那是一个以你的榜样占据一个国家的人。

希望这可以帮助。

您可以使用this来调用同一对象上的其他构造函数。 一般的想法是在最复杂的构造函数中进行属性/字段的实际初始化,并逐渐将更简单的链接一起给出默认值。

假设Countries是一个枚举,例如:

 public enum Countries { NotSet = 0, UK, US } 

你可以这样做(注意你的枚举不必有一个默认状态,如NotSet ,但如果它没有,你只需要确定如果没有指定值,默认值是什么):

 public Address() :this(String.Empty,String.Empty,String.Empty) { } public Address(string street, string city, string zip) :this(street,city,zip,Countries.NotSet) { } public Address(string street, string city, string zip, Countries country) { m_street = street; m_city = city m_zipCode = zip; m_country = country; } 

你需要括号用于构造函数链接,如下所示:

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

此外,您正在调用具有6个参数的构造函数。