代码之家  ›  专栏  ›  技术社区  ›  Jamie Ide

使用集合初始值设定项时是否推断初始容量?

c#
  •  4
  • Jamie Ide  · 技术社区  · 16 年前

    在C#3.0中使用集合初始值设定项时,是否根据用于初始化集合的元素数推断集合的初始容量?例如,是

    List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    

    List<int> digits = new List<int>(10) { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    
    2 回复  |  直到 16 年前
        1
  •  4
  •   Samuel Neff    16 年前

    号码

    List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    

    List<int> temp = new List<int>();
    temp.Add(0);
    temp.Add(1);    
    temp.Add(2);    
    temp.Add(3);    
    temp.Add(4);    
    temp.Add(5);    
    temp.Add(6);    
    temp.Add(7);    
    temp.Add(8);    
    temp.Add(9);    
    List<int> digits = temp;
    

    List<int> digits = new List<int>(32) { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
    
        2
  •  4
  •   Jon Skeet    16 年前

    不,它相当于:

    // Note the () after <int> - we're calling the parameterless constructor
    List<int> digits = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    

    换句话说,C#编译器不知道或不关心无参数构造函数将做什么,但它将调用它。这取决于集合本身来决定其初始容量是多少(如果它甚至有这样的概念——例如,链表没有)。