构造函数内部或外部的成员初始化

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)

Red*_*dog 5

我更喜欢使用构造函数。

这是因为我们残酷地发现的一个问题是,通过序列化程序(在本例中为数据契约序列化程序)重建的对象没有调用其字段初始值设定项。

此外,它还确保所有初始化逻辑相应地组合在一起,而不是潜在地散布在整个代码中(无论您想在哪里定义字段变量)。


Mat*_*hen 2

由于您在显式构造函数中有其他代码(“其他对象创建代码”),因此我更愿意将所有初始化放在那里。