开发者

Is the initial capacity inferred when using collection initializers?

When using the collection initializers in C# 3.0, is the initial capacity of the collection inferred from the number of elements used to initialize the collection? For example, is

List<int开发者_运维百科> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

equivalent to

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


No.

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

is equivalent to

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;

The number of items being added doesn't automatically change the initial capacity. If you're adding more than 16 items through the collection initializer you can combine the constructor and initializer like this:

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


No, it's equivalent to:

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

In other words, the C# compiler doesn't know or care what the parameterless constructor will do - but that's what it will call. It's up to the collection itself to decide what its initial capacity is (if it even has such a concept - a linked list doesn't, for example).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜