List<T>.Item[Int32] 屬性

定義

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

public:
 property T default[int] { T get(int index); void set(int index, T value); };
public T this[int index] { get; set; }
member this.Item(int) : 'T with get, set
Default Public Property Item(index As Integer) As T

參數

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[] 實作為預設屬性,這樣會提供相同的索引功能。

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");
Dim dinosaurs As New List(Of String)

Console.WriteLine(vbLf & "Capacity: {0}", dinosaurs.Capacity)

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

備註

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

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

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

適用於

另請參閱