List
列表的属性:
- 它与数组不同。列表可以动态调整大小,但数组则不能。
- 列表类可以接受null作为引用类型的有效值,并且还允许重复的元素。
- 如果计数等于容量,则列表的容量将通过重新分配内部数组而自动增加。在添加新元素之前,现有元素将被复制到新数组。
容量与数量:
- 计数始终小于容量。添加元素时,如果Count超过Capacity,则在复制旧元素并添加新元素之前,通过重新分配内部数组,Capacity将自动增加。
- 容量是在调整所需列表大小之前列表可以存储的元素数。但是Count是列表中实际存在的元素数。
- 如果“容量”远大于“计数”,则用户可以通过调用TrimExcess方法或将“容量”显式设置为较低的值来减少容量。
- 如果明确地确定了Capacity,则内部数组也将重新分配以容纳指定的容量,并复制所有元素。
- 检索Capacity属性的值是O(1)操作,而将Capacity设置为O(n)操作,其中n是新的容量。
句法:
public int Capacity { get; set; }
返回值:该方法返回类型为System.Int32的大小需要调整之前List
例外情况:
- ArgumentOutOfRangeException:如果将容量设置为小于Count的值。
- OutOfMemoryException:如果系统上没有足够的可用内存。
以下程序说明了“容量属性”的用法:
范例1:
// C# program to illustrate the
// Capacity Property of List
using System;
using System.Collections.Generic;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// Creating a List of integers
// Here we are not setting
// Capacity explicitly
List firstlist = new List();
// adding elements in firstlist
firstlist.Add(1);
firstlist.Add(2);
firstlist.Add(3);
firstlist.Add(4);
// Printing the Capacity of firstlist
Console.WriteLine("Capacity Is: " + firstlist.Capacity);
// Printing the Count of firstlist
Console.WriteLine("Count Is: " + firstlist.Count);
// Adding some more
// elements in firstlist
firstlist.Add(5);
firstlist.Add(6);
// Printing the Capacity of firstlist
// It will give output 8 as internally
// List is resized
Console.WriteLine("Capacity Is: " + firstlist.Capacity);
// Printing the Count of firstlist
Console.WriteLine("Count Is: " + firstlist.Count);
}
}
输出:
Capacity Is: 4
Count Is: 4
Capacity Is: 8
Count Is: 6
范例2:
// C# program to illustrate the
// Capacity Property of List
using System;
using System.Collections.Generic;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// Creating a List of integers
// Here we are setting Capacity
// explicitly i.e.
List firstlist = new List(10);
// Printing the Capacity of firstlist
Console.WriteLine("Capacity Is: " + firstlist.Capacity);
// Printing the Count of firstlist
Console.WriteLine("Count Is: " + firstlist.Count);
// adding elements in firstlist
firstlist.Add(1);
firstlist.Add(2);
firstlist.Add(3);
firstlist.Add(4);
// Printing the Capacity of firstlist
Console.WriteLine("Capacity Is: " + firstlist.Capacity);
// Printing the Count of firstlist
Console.WriteLine("Count Is: " + firstlist.Count);
// Adding some more
// elements in firstlist
firstlist.Add(5);
firstlist.Add(6);
// Printing the Capacity of firstlist
// It will give output 10 as we have
// already set the Capacity
Console.WriteLine("Capacity Is: " + firstlist.Capacity);
// Printing the Count of firstlist
Console.WriteLine("Count Is: " + firstlist.Count);
}
}
输出:
Capacity Is: 10
Count Is: 0
Capacity Is: 10
Count Is: 4
Capacity Is: 10
Count Is: 6
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.list-1.capacity?view=netframework-4.7.2