Answers:
真的很简单:
myList.Clear();
List<>,ArrayList或器具IList。;)
List<T>.Clear正确清除所有引用,这使GC可以在必要时清除分配。new List<T>不能做到这一点,并且不适用于所有情况
如果通过“列表”表示a List<T>,那么Clear方法就是您想要的:
List<string> list = ...;
...
list.Clear();
您应该养成在这些方面搜索MSDN文档的习惯。
以下是快速搜索有关该类型各个位的文档的方法:
List<T>类本身(这是您应该开始的地方)所有这些Google查询都列出了一系列链接,但通常情况下,您都希望google提供给您的第一个链接。
给出替代答案(谁需要5个相等的答案?):
list.Add(5);
// list contains at least one element now
list = new List<int>();
// list in "list" is empty now
请记住,对旧列表的所有其他引用都尚未清除(取决于情况,这可能是您想要的)。同样,在性能方面,它通常会慢一些。
list一句,也请牢记有新参考。因此,如果要在该列表上使用锁,请不要使用它。
选项1:使用Clear()函数清空List<T>并保留其容量。
Count设置为0,并且也会释放对集合元素中其他对象的引用。
容量保持不变。
选项2-使用Clear()和TrimExcess()函数设置List<T>为初始状态。
Count设置为0,并且也会释放对集合元素中其他对象的引用。
修剪为空会将
List<T>列表的容量设置为默认容量。
定义
Count =实际存在于元素中的元素数List<T>
容量 =内部数据结构无需调整大小即可容纳的元素总数。
仅Clear()
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Compsognathus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Deinonychus");
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
dinosaurs.Clear();
Console.WriteLine("\nClear()");
Console.WriteLine("\nCount: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Clear()和TrimExcess()
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Triceratops");
dinosaurs.Add("Stegosaurus");
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
dinosaurs.Clear();
dinosaurs.TrimExcess();
Console.WriteLine("\nClear() and TrimExcess()");
Console.WriteLine("\nCount: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);