List<T>.Item[Int32] 屬性
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
取得或設定位於指定索引處的專案。
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
位於指定索引的元素。
實作
例外狀況
範例
本節範例展示了 Item[] 該泛類的性質(C# 中的索引器)以及其他各種性質與方法 List<T> 。 在使用 Add 該方法建立並填充清單後,會擷取一個元素並使用 該 Item[] 屬性顯示。 (關於使用該 Item[] 屬性設定列表元素值的範例,請參見 AsReadOnly。)
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) 操作。