End*_*ace 5 .net c# coding-style
两种初始化哪一种更好?
public class ServiceClass
{
private DataManager dataManager = new DataManager();
private Dictionary<string, string> stringDictionary = new Dictionary<string, string>();
private Dictionary<string, DateTime> timeDictionary = new Dictionary<string, DateTime>();
public ServiceClass()
{
//other object creation code
}
}
Run Code Online (Sandbox Code Playgroud)
或者
public class ServiceClass
{
private DataManager dataManager;
private Dictionary<string, string> stringDictionary;
private Dictionary<string, DateTime> timeDictionary;
public ServiceClass()
{
dataManager = new DataManager();
stringDictionary = new Dictionary<string, string>();
timeDictionary = new Dictionary<string, DateTime>();
//other object creation code
}
}
Run Code Online (Sandbox Code Playgroud)
我更喜欢使用构造函数。
这是因为我们残酷地发现的一个问题是,通过序列化程序(在本例中为数据契约序列化程序)重建的对象没有调用其字段初始值设定项。
此外,它还确保所有初始化逻辑相应地组合在一起,而不是潜在地散布在整个代码中(无论您想在哪里定义字段变量)。
| 归档时间: |
|
| 查看次数: |
1221 次 |
| 最近记录: |