List
列表的属性:
- 它与数组不同。列表可以动态调整大小,但数组则不能。
- 列表类可以接受null作为引用类型的有效值,并且还允许重复的元素。
- 如果计数等于容量,则列表的容量将通过重新分配内部数组而自动增加。在添加新元素之前,现有元素将被复制到新数组。
句法:
public T this[int index] { get; set; }
范围:
index: It is the zero-based index of the element to get or set of type System.Int32.
返回值:该属性返回指定索引处的元素。
异常:如果索引小于0或索引等于或大于Count,则此方法将提供ArgumentOutOfRangeException 。
下面的示例说明了List
范例1:
// C# program to illustrate the
// List.Item[32] property
using System;
using System.Collections.Generic;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// Creating a List of Strings
List firstlist = new List();
// adding elements in firstlist
firstlist.Add("A");
firstlist.Add("B");
firstlist.Add("C");
firstlist.Add("D");
firstlist.Add("E");
firstlist.Add("F");
// getting the element of
// firstlist using Item property
Console.WriteLine("Element at index 2: " + firstlist[2]);
}
}
输出:
Element at index 2: C
范例2:
// C# program to illustrate the
// List.Item[32] property
using System;
using System.Collections.Generic;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// Creating a List of String
List firstlist = new List();
// adding elements in firstlist
firstlist.Add("A");
firstlist.Add("B");
firstlist.Add("C");
firstlist.Add("D");
firstlist.Add("E");
firstlist.Add("F");
// Before setting the another
// value of index 2 we will get
// the element of firstlist
// using Item property
Console.WriteLine("Element at index 2: " + firstlist[2]);
// setting the value of Element
firstlist[2] = "Z";
// displaying the updated value
Console.WriteLine("After Setting the new value at 2: " + firstlist[2]);
}
}
输出:
Element at index 2: C
After Setting the new value at 2: Z
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.list-1.item?view=netframework-4.7.2