List<T>.容量实现

List<T>.Capacity implementation

我正在查看 List<T> 的源代码。它有 属性:

public int Capacity {
get {
    Contract.Ensures(Contract.Result<int>() >= 0);
    return _items.Length;
}
set {
    if (value < _size) {
        ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity);
    }
    Contract.EndContractBlock();

    if (value != _items.Length) {
        if (value > 0) {
            T[] newItems = new T[value];
            if (_size > 0) {
                Array.Copy(_items, 0, newItems, 0, _size);
            }
            _items = newItems;
        }
        else {
            _items = _emptyArray;
        }
    }
}

}

检查 if (value > 0) 的意义何在,就好像由于检查 if (value < _size) 而永远不会达到此代码的情况?

您忘记了 value_size 均为 0 的情况。请参阅引用 _emptyArrayelse 块。这处理如下所示的情况。

var list = new List<string>(16);
Debug.Assert(list.Count == 0);
Debug.Assert(list.Capacity == 16);
list.Capacity = 0;