2010-11-11 41 views

回答

8

容量将增加一倍。

这是通过下面的源控制:

// Ensures that the capacity of this list is at least the given minimum 
// value. If the currect capacity of the list is less than min, the 
// capacity is increased to twice the current capacity or to min, 
// whichever is larger. 
private void EnsureCapacity(int min) { 
    if (_items.Length < min) { 
     int newCapacity = _items.Length == 0? _defaultCapacity : _items.Length * 2; 
     if (newCapacity < min) newCapacity = min; 
     Capacity = newCapacity; 
    } 
} 

_defaultCapacityconst int等于4

+1

Argghh,我不得不验证:( – leppie 2010-11-11 17:24:54

2

看起来它加倍,基于以下的代码:

int initialCapacity = 100; 
List<string> list = new List<string>(initialCapacity); 

Console.WriteLine(list.Capacity); 

for(int i = 0; i < list.Capacity; i++){ 
    list.Add("string " + i);  
} 

list.Add("another string"); 

Console.WriteLine(list.Capacity); // shows 200, changes based on initialCapacity 
4

这是EnsureCpacity方法作为反射器看到它。大小将翻倍:)

private void EnsureCapacity(int min) 
{ 
    if (this._items.Length < min) 
    { 
     int num = (this._items.Length == 0) ? 4 : (this._items.Length * 2); 
     if (num < min) 
     { 
      num = min; 
     } 
     this.Capacity = num; 
    } 
}