List<T>.Item[Int32] List<T>.Item[Int32] List<T>.Item[Int32] List<T>.Item[Int32] Property

定義

在指定的索引位置上取得或設定項目。Gets or sets the element at the specified index.

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 Int32 Int32 Int32

要取得或設定之以零為起始的項目索引。The zero-based index of the element to get or set.

屬性值

T T T T

在指定索引上的項目。The element at the specified index.

實作

例外狀況

index 小於 0。index is less than 0.

-或--or- index 等於或大於 Countindex is equal to or greater than Count.

範例

在本節中的範例會示範Item[Int32]屬性 (C# 中為索引子) 和各種其他的屬性和方法List<T>泛型類別。The example in this section demonstrates the Item[Int32] property (the indexer in C#) and various other properties and methods of the List<T> generic class. 清單已建立並填入使用Add方法中,項目會擷取並顯示使用Item[Int32]屬性。After the list has been created and populated using the Add method, an element is retrieved and displayed using the Item[Int32] property. (如需使用的範例Item[Int32]屬性來設定元素的值清單,請參閱AsReadOnly。)(For an example that uses the Item[Int32] property to set the value of a list element, see AsReadOnly.)

注意

Visual Basic 中, C#,和C++都有存取語法Item[Int32]而不使用其名稱的屬性。Visual Basic, C#, and C++ all have syntax for accessing the Item[Int32] property without using its name. 相反地,變數包含List<T>用於陣列一樣。Instead, the variable containing the List<T> is used as if it were an array.

C#語言會使用 this 關鍵字來定義索引,而不必實作Item[Int32]屬性。The C# language uses the this keyword to define the indexers instead of implementing the Item[Int32] property. Visual Basic 會將 Item[Int32] 實作為預設屬性,這樣會提供相同的索引功能。Visual Basic implements Item[Int32] as a default property, which provides the same indexing functionality.

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參考有效的值類型,並允許重複的項目。List<T> accepts null as a valid value for reference types and allows duplicate elements.

這個屬性可以使用下列語法提供存取集合中特定元素的能力:myCollection[index]This property provides the ability to access a specific element in the collection by using the following syntax: myCollection[index].

擷取這個屬性的值是 o (1) 的作業;設定屬性,也是 o (1) 作業。Retrieving the value of this property is an O(1) operation; setting the property is also an O(1) operation.

適用於

另請參閱