【发布时间】:2011-11-26 12:25:06
【问题描述】:
【问题讨论】:
标签: c# java oop coding-style constructor
【问题讨论】:
标签: c# java oop coding-style constructor
这绝对是一个好习惯,主要有两个原因:
避免代码重复
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;
}
}
希望对您有所帮助 - 它可以减少重复。
此处显示了一个更“极端”的示例,其中包含许多字段(以及许多潜在的重复项):
【讨论】:
null 而不是 "" 传递给链式构造函数
当您在施工期间完成一些繁重的工作时,我已经看到它,并且您有很多不同的方法来创建对象。 (所以少数具有不同参数签名的ctors)。
您可以只拥有一个私有成员函数,它可以跨 ctor 完成共同工作。你真的不需要让一个演员在同一个班级里打电话给另一个。 (大多数语言甚至都不允许这样做)。
【讨论】: