List<T>.Item[Int32] 屬性

定義

在指定的索引位置上取得或設定項目。

C#
public T this[int index] { get; set; }

參數

index
Int32

要取得或設定的以零為起始元素索引。

屬性值

T

在指定索引上的項目。

實作

例外狀況

index 小於 0。

-或-

index 等於或大於 Count

範例

本節中的範例示範 Item[] 屬性 (C#) 中的索引器,以及泛型類別的各種其他屬性和方法 List<T> 。 使用 Add 方法建立並填入清單之後,會使用 Item[] 屬性擷取並顯示專案。 (如需使用 Item[] 屬性來設定清單元素值的範例,請參閱 AsReadOnly.)

備註

Visual Basic、C# 和 C++ 都有用來存取 Item[] 屬性的語法,而不使用其名稱。 而是使用包含的 List<T> 變數,就像是數位一樣。

C# 語言使用 this 關鍵字定義索引,而不必實作 Item[] 屬性。 Visual Basic 會將 Item[] 實作為預設屬性,這樣會提供相同的索引功能。

C#
List<string> dinosaurs = new List<string>();

Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);

dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");
C#
// Shows accessing the list using the Item property.
Console.WriteLine("\ndinosaurs[3]: {0}", dinosaurs[3]);

備註

List<T> 接受 null 作為參考型別的有效值,並允許重複的專案。

這個屬性可透過下列語法存取集合中的特定元素:myCollection[index]

擷取此屬性的值是 O (1) 作業;設定 屬性也是 O (1) 作業。

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

另請參閱