考慮看看的源代碼清單(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