您的位置:首页 > Web前端

Item 12:Perfer Variable Initializers to Assignment Statements

2005-08-12 18:53 330 查看
编译器总是在运行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时

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.


public class MyClass
public class MyClass
private ArrayList _col;

MyClass()
_col = new ArrayList();
}

MyClass(int size)
_col = new ArrayList();
_col = new ArrayList(size);
}
}
[b]3.如果一个成员变量初始化时很容易出错,就尽量不要使用initialization。 [/b]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐