[英]Purpose of Constructor chaining?
这绝对是个好习惯,主要有两个原因:
避免代码重复
class Foo
{
public Foo(String myString, Int32 myInt){
//Some Initialization stuff here
}
//Default value for myInt
public Foo(String myString) : this(myString, 42){}
//Default value for both
public Foo() : this("The Answer", 42){}
}
实施良好的封装
public abstract class Foo
{
protected Foo(String someString)
{
//Important Stuff Here
}
}
public class Bar : Foo
{
public Bar(String someString, Int32 myInt): base(someString)
{
//Let's the base class do it's thing
// while extending behavior
}
}
主要原因是能够在构造函数之间重用代码。 您可以将所有初始化代码放在一个构造函数中,然后从其他构造函数调用该初始化代码,而不是重复初始化。
“构造函数链接”是一种方法,通过该方法构造函数可以调用同一类中的另一个构造函数。 当我们有一个定义多个构造函数的类时,这特别有用。 例如,在下面的示例中,我们将创建一个名为Person的类。 我们还可以使用三个字段: 年龄,姓名和颜色。 此类具有三个构造函数。 如果我们不使用“构造函数链接”方法,则代码将如下所示:
不使用构造函数链接:
public class Person
{
private int Age;
private string Name;
private string HairColour;
public Person(int theAge)
{
Age = theAge;
}
public Person(int theAge, string theName)
{
Age = theAge;
Name = theName;
}
public Person(int theAge, string theName, string theHairColour)
{
Age = theAge;
Name = theName;
HairColour = theHairColour;
}
}
如您所见,在每个构造函数中,我们都为Age分配了一个值,该值与代码重复。 我们还在两个构造函数中为Name分配了一个值,因此再次重复。 为了消除此问题,我们可以在构造函数中使用最多参数将所有值分配给Age,Name和HairColour。 然后,当其他两个构造函数被调用时,我们可以调用该构造函数。 请参见下面的代码,以了解这种“链式”方法。
使用构造函数链接:
public class Person
{
private int Age;
private string Name;
private string HairColour;
public Person(int theAge):this(theAge, "", "")
{
//One parameter
}
public Person(int theAge, string theName):this(theAge, theName, "")
{
//Two Parameters
}
public Person(int theAge, string theName, string theHairColour)
{
//Three parameters
Age = theAge;
Name = theName;
HairColour = theHairColour;
}
}
希望能有所帮助-节省重复步骤。
此处显示了一个具有更多字段(以及很多潜在重复项)的更“极端”示例:
当您在构造时完成一些繁重的工作并且创建对象的方法有很多时,我已经看到了。 (因此,具有不同参数签名的ctor很少)。
您只能拥有一个私有成员函数,该函数可以在各个ctor之间执行常见的工作。 您实际上不需要在同一个班级中让一个ctor呼叫另一个。 (大多数语言甚至都不允许使用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.