【问题标题】:member initialization inside or outside the constructor构造函数内部或外部的成员初始化
【发布时间】:2010-12-16 02:34:52
【问题描述】:

两种初始化中哪一种更好?

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
    }
}

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
    }
}

【问题讨论】:

标签: c# .net coding-style


【解决方案1】:

我更喜欢使用构造函数。

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-30
      • 2014-12-12
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多