我正在查看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),这段代码永远不会到达。
发布于 2015-11-13 16:32:05
当value和_size都为0时,您忘记了这种情况。请参阅引用else的_emptyArray块。这将处理下面所示的情况。
var list = new List<string>(16);
Debug.Assert(list.Count == 0);
Debug.Assert(list.Capacity == 16);
list.Capacity = 0;https://stackoverflow.com/questions/33697400
复制相似问题