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

C# 使用集合初始值设定项时是否推断初始容量?,c#,C#,在C#3.0中使用集合初始值设定项时,是否根据用于初始化集合的元素数推断集合的初始容量?例如,是 List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; List digits=新列表{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,

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

List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List digits=新列表{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 };
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 digits=新列表(10){0,1,2,3,4,5,6,7,8,9};

不,它相当于:

// 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 };
//注意-后面的()我们正在调用无参数构造函数
列表位数=新列表(){0,1,2,3,4,5,6,7,8,9};
换句话说,C#编译器不知道或不关心无参数构造函数将做什么,但它将调用它。由集合本身决定其初始容量是多少(如果它甚至有这样的概念,例如,链表就没有)

List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List digits=新列表{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 };
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 temp=new List();
临时添加(0);
临时添加(1);
临时添加(2);
临时添加(3);
临时添加(4);
临时添加(5);
临时添加(6);
临时添加(7);
临时添加(8);
临时添加(9);
列表数字=温度;
添加的项目数不会自动更改初始容量。如果要通过集合初始值设定项添加16个以上的项,可以将构造函数和初始值设定项组合起来,如下所示:

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 };
List digits=新列表(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};

这个答案有点不完整<代码>列表数字=新列表{0,1,2,3,4,5,6,7,8,9}相当于
列表位数=新列表();数字。添加(0);数字。添加(1)。。。数字。增加(9)构造函数从未看到集合初始值设定项列表的元素。因此,从构造函数的角度来看,初始值设定项列表在确定初始容量方面不起作用。@Jason,实际上它相当于使用一个临时变量来调用构造函数,添加项,然后将临时值赋回原始变量。这里的区别是,如果在一个Add()调用中发生错误,temp会自动丢弃(因为没有对它的引用),变量“digits”也不会被赋值。这个答案只是为了解决构造函数调用,因为问题是比较具有显式构造函数参数列表的集合初始值设定项与不具有参数列表的集合初始值设定项。可能存在重复的