語言

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。)

Note

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 planets As New List(Of String)

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

planets.Add("Mercury")
planets.Add("Venus")
planets.Add("Earth")
planets.Add("Mars")
planets.Add("Jupiter")
// 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 & "planets(3): {0}", planets(3))

備註

List<T> 接受 null 作為參考類型的有效值,並允許重複元素。

此特性可透過以下語法存取集合中的特定元素: myCollection[index]。

取得此屬性的值為 O(1) 運算;設定屬性也是 O(1) 操作。

適用於

另請參閱