构造函数链的目的是什么?

在阅读了这个构造函数链接问题后,我只是想知道为什么会有人进行构造函数链接?

有人可以对可能有用的情景类型有所了解。

这是一个很好的编程习惯吗?

这绝对是一个好习惯,主要有两个原因:

避免代码重复

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的类。 我们还有三个可以使用的领域; 年龄,姓名和头发颜色。 这个类有三个构造函数。 如果我们没有使用’Constructor Chaining’方法,代码将如下所示:

不使用构造函数链接:

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

希望有所帮助 – 它可以节省重复。

这里显示了一个包含大量字段(以及大量潜在重复)的更“极端”的示例:

一个例子,它肯定会节省重复

当你在施工时完成一些繁重的工作时,我已经看到了它,你有很多不同的方法来创造这个物体。 (少数具有不同参数签名的ctors)。

你可以拥有一个私人会员function,可以在ctors之间完成共同的工作。 你真的不需要让一个ctor在同一个类中调用另一个。 (大多数语言都不允许这样做)。