Collection < T > .Clear方法用于从Collection < T >中删除所有元素。
句法:
public void Clear ();
下面给出了一些示例,以更好地理解实现:
范例1:
// C# code to remove all
// elements from the Collection
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");
// To print the count of elements in Collection
Console.WriteLine("Count : " + myColl.Count);
// Displaying the elements in myColl
foreach(string str in myColl)
{
Console.WriteLine(str);
}
// Removing all the elements from Collection
myColl.Clear();
// To print the count of elements in Collection
Console.WriteLine("Count : " + myColl.Count);
// Displaying the elements in myColl
foreach(string str in myColl)
{
Console.WriteLine(str);
}
}
}
输出:
Count : 5
A
B
C
D
E
Count : 0
范例2:
// C# code to remove all
// elements from the Collection
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);
// To print the count of elements in Collection
Console.WriteLine("Count : " + myColl.Count);
// Displaying the elements in myColl
foreach(int i in myColl)
{
Console.WriteLine(i);
}
// Removing all the elements from Collection
myColl.Clear();
// To print the count of elements in Collection
Console.WriteLine("Count : " + myColl.Count);
// Displaying the elements in myColl
foreach(int i in myColl)
{
Console.WriteLine(i);
}
}
}
输出:
Count : 4
2
3
4
5
Count : 0
笔记:
- Count设置为零,并且还会释放对集合元素中其他对象的引用。
- 此方法是O(n)运算,其中n是Count。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.objectmodel.collection-1.clear?view=netframework-4.7.2