编译器总是在运行Constructor前,先初始化成员变量(不包括静态变量)。当有初始化语句时,你不需要为每个构造函数添加初始化语句。Equally important,the initializers are added to the complier-generated default constructor.The C# complier creates a default constructor for you types whenever you don't explicitly define any constructors.
注意:有三种情况不适合使用initializer
1.当对象或变量被初始化为null或0时
3.如果一个成员变量初始化时很容易出错,就尽量不要使用initialization。
注意:有三种情况不适合使用initializer
1.当对象或变量被初始化为null或0时
MyValueType _myclass; //initicalized to 0
MyValueType _myclass = new MyValueType(); //also 0
The default system initialization sets everything to 0(null) for you before any of your code executes.
如果你添加了额外的初始化语句(如第二种)C#编译器必需添加额外的语句去把变量重新初始化为0
2.You should use the initializer syntax only for variables that receive the same initialization in all constructor.
在以上这种情况中,如果你使用的是第二个构造函数,则刚刚初始化的_col立刻变成了垃圾。可以把上面的代码看成一下这种形式MyValueType _myclass = new MyValueType(); //also 0
The default system initialization sets everything to 0(null) for you before any of your code executes.
如果你添加了额外的初始化语句(如第二种)C#编译器必需添加额外的语句去把变量重新初始化为0
2.You should use the initializer syntax only for variables that receive the same initialization in all constructor.
public class MyClass
{
private ArrayList _col = new ArratList();
MyClass()
{
}
MyClass(int size)
{
_col = new ArrayList(size);
}
}
{
private ArrayList _col = new ArratList();
MyClass()
{
}
MyClass(int size)
{
_col = new ArrayList(size);
}
}
public class MyClass
{
private ArrayList _col;
MyClass()
{
_col = new ArrayList();
}
MyClass(int size)
{
_col = new ArrayList();
_col = new ArrayList(size);
}
}
{
private ArrayList _col;
MyClass()
{
_col = new ArrayList();
}
MyClass(int size)
{
_col = new ArrayList();
_col = new ArrayList(size);
}
}
3.如果一个成员变量初始化时很容易出错,就尽量不要使用initialization。