在构造函数中初始化私有集合,重复或使用链接?

时间:2013-12-12 17:15:59

标签: c#

我有一个类:

public class Something
{
   private Dictionary<int,int> dic;

   public Something() 
   {
         dic = new Dictionary<int,int>();
   }

   public Something(Dictionary<int,int> a)
  {
         dic = new Dictionary<int,int>();

   }

}

如何避免两次初始化集合?

3 个答案:

答案 0 :(得分:3)

我猜您正在寻找chaining constructor

public class Something
{
    private Dictionary<int, int> dic;

    public Something()
        : this(new Dictionary<int, int>())
    {
    }

    public Something(Dictionary<int, int> a)
    {
        dic = a;
    }
}

答案 1 :(得分:2)

致电this()

public Something() 
{
      dic = new Dictionary<int,int>();
}

public Something(Dictionary<int,int> a) : this()
{
     // do something with a??
}

请注意,默认情况下,“默认”构造函数不会被其他构造函数调用,因此您并未真正初始化字典两次

答案 2 :(得分:0)

还有另一种选择:

public class Something
{
    private Dictionary<int, int> dic;

    private void Initialize()
    {
        dic = new Dictionary<int, int>();
    }

    public Something()
    {
        Initialize();
    }

    public Something(Dictionary<int, int> a)
    {
        Initialize();
        // do something with a??
        // Yes, you are not using the parameter "a".
        // I don't know if this is intentional.
    }
}

注意:这不适用于readonly字段。


顺便说一下,I mentioned可以chain the constructors。{{3}}。编译器可以优化它。