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 |