4
2個初始化中的哪一個更好?構造函數內部或外部的成員初始化
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
}
}
OR
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
}
}
[最佳實踐:初始化構造函數或聲明中的類字段?]的可能的重複?(http://stackoverflow.com/questions/24551/best-practice-initialize-class-fields-in-constructor-or-at -宣言) – Gishu 2010-12-16 02:49:04