Collection < T > .Item [Int32]属性用于获取或设置指定索引处的元素。
句法:
public T this[int index] { get; set; }
在这里, index是要获取或设置的元素的从零开始的索引。
返回值:指定索引处的元素。
异常:如果索引小于零或索引等于或大于Count,则此方法将提供ArgumentOutOfRangeException。
下面给出了一些示例,以更好地理解实现:
范例1:
// C# code to get or set the
// element at the specified index
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
// Driver code
public static void Main()
{
// Creating a collection of strings
Collection myColl = new Collection();
// Adding elements in Collection myColl
myColl.Add("A");
myColl.Add("B");
myColl.Add("C");
myColl.Add("D");
myColl.Add("E");
// Displaying the elements in myColl
foreach(string str in myColl)
{
Console.WriteLine(str);
}
// Get the element at index 2
Console.WriteLine("Element at index 2 is : " + myColl[2]);
// Get the element at index 3
Console.WriteLine("Element at index 3 is : " + myColl[3]);
// Set the element at index 3
myColl[3] = "GFG";
// Displaying the elements in myColl
foreach(string str in myColl)
{
Console.WriteLine(str);
}
}
}
输出:
A
B
C
D
E
Element at index 2 is : C
Element at index 3 is : D
A
B
C
GFG
E
范例2:
// C# code to get or set the
// element at the specified index
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
// Driver code
public static void Main()
{
// Creating a collection of ints
Collection myColl = new Collection();
// Adding elements in Collection myColl
myColl.Add(2);
myColl.Add(3);
myColl.Add(4);
myColl.Add(5);
// Displaying the elements in myColl
foreach(int i in myColl)
{
Console.WriteLine(i);
}
// Get the element at index -1
// This should raise "ArgumentOutOfRangeException"
// as the index is less than 0
Console.WriteLine("Element at index -1 is : " + myColl[-1]);
// Set the element at index 2
myColl[2] = 10;
// Displaying the elements in myColl
foreach(int i in myColl)
{
Console.WriteLine(i);
}
}
}
运行时错误:
Unhandled Exception:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
笔记:
- Collection < T >接受null作为引用类型的有效值,并允许重复的元素。
- 通过使用以下语法,可以使用此属性访问集合中的特定元素: myCollection [index] 。
- 检索此属性的值是O(1)操作。
- 设置属性也是O(1)操作。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.objectmodel.collection-1.item?view=netframework-4.7.2