Effective C# 学习笔记(十四) 尽量减少重复性的初始化逻辑

对于构造函数的复合调用,尽量少写,因为其会影响运行效率,因为运行的代码更多了。你可以这样调用。

 

//构造函数复合调用示例

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以前,可以使用thisbase关键字来调用唯一实现逻辑的重载构造函数,而不会引起多次多层调用重载的构造函数,它也不会把实例变量的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;

}

}

对于静态成员变量,还要考虑到其只可初始化一次,所以不可在重载的构造函数中对静态成员变量赋值,哪怕只有一个唯一实现的构造函数。这时,只可利用隐式成员变量初始化方式初始化静态成员变量。

原文地址:https://www.cnblogs.com/haokaibo/p/2098734.html