考虑看看的源代码清单(T)的,你看到的索引属性的getter/setter方法是这样的:
// Sets or Gets the element at the given index.
//
public T this[int index] {
get {
// Fllowing trick can reduce the range check by one
if ((uint) index >= (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException();
}
return _items[index];
}
set {
if ((uint) index >= (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException();
}
_items[index] = value;
_version++;
}
}
注意,之前设置在列表内部的相应项目数组,它首先检查私人_size
变量以确保它在范围内。但是,_size
未设置为阵列的大小。大小在列表的各种添加/删除方法中增加/减少,因此即使您初始化一个初始容量为10的列表,即列表数组的容量为内部。下面是构造函数:
// Constructs a List with a given initial capacity. The list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required.
//
public List(int capacity) {
if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_SmallCapacity);
_items = new T[capacity];
}
的_size
没有设置(并因此保持为0的初始值),除非您使用添加/删除/的AddRange /等。或者使用接受IEnumerable的构造函数(在这种情况下,因为IEnumerable中的项数)。
如果你仔细想想,这是有道理的。列表的想法是,您不必担心数字索引的复杂性(和丑陋),并在容量需要更改时调整/复制数组。在实例化List之后,内部数组的大小应该与开发人员无关。如果您想微观管理内部数组的使用方式,那么您应该创建自己的实现,或者只使用一个数组。
来源
2016-05-16 20:26:36
DVK
'不应该都具有相同的行为吗?不。为什么它应该是相同的?它们不是同一个东西... – Eser
您需要先将字符串“asdf”添加到x,然后才能使用它。 x.add( “ASDF”)。现在列表是空的。 – Auguste
为什么你会认为他们会有相同的行为?列表和数组是不同的东西。 – itsme86