List<T>.Item[Int32] 屬性
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
在指定的索引位置上取得或設定項目。
public:
property T default[int] { T get(int index); void set(int index, T value); };
C#
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
在指定索引上的項目。
本節中的範例示範 Item[] 屬性 (C#) 中的索引器,以及泛型類別的各種其他屬性和方法 List<T> 。 使用 Add 方法建立並填入清單之後,會使用 Item[] 屬性擷取並顯示專案。 (如需使用 Item[] 屬性來設定清單元素值的範例,請參閱 AsReadOnly.)
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");
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")
C#
// 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) 作業。
產品 | 版本 |
---|---|
.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 |