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

适用于

另请参阅