List<T>.Item[Int32] 属性

定义

获取或设置指定索引处的元素。

C#
public T this[int index] { get; set; }

参数

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[] 实现为默认属性,该属性提供相同的索引功能。

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");
C#
// Shows accessing the list using the Item property.
Console.WriteLine("\ndinosaurs[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

另请参阅