Effective C# 学习笔记(十四) 尽量减少重复性的初始化逻辑
2011-07-05 22:55 小郝(Kaibo Hao) 阅读(306) 评论(0) 编辑 收藏 举报对于构造函数的复合调用,尽量少写,因为其会影响运行效率,因为运行的代码更多了。你可以这样调用。
//构造函数复合调用示例
public class MyClass
{
// collection of data
private List<ImportantData> coll;
// Name of the instance:
private string name;
public MyClass() :
this(0, "")
{
}
public MyClass(int initialCount) :
this(initialCount, string.Empty)
{
}
public MyClass(int initialCount, string name)
{
coll = (initialCount > 0) ?
new List<ImportantData>(initialCount) :
new List<ImportantData>();
this.name = name;
}
}
//利用C#4.0新特性—参数默认值简化构造函数重载的复杂度,以减少重载过多带来的代码维护的工作量
public class MyClass
{
// collection of data
private List<ImportantData> coll;
// Name of the instance:
private string name;
// Needed to satisfy the new() constraint.
public MyClass() :
this(0, string.Empty)
{
}
//注意这里的name参数用了"",而不是string.Empty作为默认值,这是由于string.Empty不是一个编译时的常量,所以不能作为默认参数值
public MyClass(int initialCount = 0, string name = "")
{
coll = (initialCount > 0) ?
new List<ImportantData>(initialCount) :
new List<ImportantData>();
this.name = name;
}
}
注意:由于在继承中new()的约束,在父类中除了带默认参数的构造函数外,还要显示地声明一个无参的构造函数,如上代码所示。
//在C#3.0以前,可以使用this或base关键字来调用唯一实现逻辑的重载构造函数,而不会引起多次多层调用重载的构造函数,它也不会把实例变量的initializer拷贝到每个构造函数中。
// Not legal, illustrates IL generated:
public class MyClass
{
private List<ImportantData> coll;
private string name;
public MyClass()
{
// No variable initializers here.
// Call the third constructor, shown below.
this(0, ""); // Not legal, illustrative only.
}
public MyClass(int initialCount)
{
// No variable initializers here.
// Call the third constructor, shown below.
this(initialCount, "");
}
public MyClass(int initialCount, string Name)
{
// Instance Initializers would go here.
object(); // Not legal, illustrative only.
coll = (initialCount > 0) ?
new List<ImportantData>(initialCount) :
new List<ImportantData>();
name = Name;
}
}
对于静态成员变量,还要考虑到其只可初始化一次,所以不可在重载的构造函数中对静态成员变量赋值,哪怕只有一个唯一实现的构造函数。这时,只可利用隐式成员变量初始化方式初始化静态成员变量。
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。