HashSet<T>.Clear 方法

定义

HashSet<T> 对象中移除所有元素。

public:
 virtual void Clear();
public void Clear ();
abstract member Clear : unit -> unit
override this.Clear : unit -> unit
Public Sub Clear ()

实现

示例

以下示例创建并填充 HashSet<T> 集合,然后清除该集合并释放该集合引用的内存。

HashSet<int> Numbers = new HashSet<int>();

for (int i = 0; i < 10; i++)
{
    Numbers.Add(i);
}

Console.Write("Numbers contains {0} elements: ", Numbers.Count);
DisplaySet(Numbers);

Numbers.Clear();
Numbers.TrimExcess();

Console.Write("Numbers contains {0} elements: ", Numbers.Count);
DisplaySet(Numbers);

void DisplaySet(HashSet<int> set)
{
    Console.Write("{");
    foreach (int i in set)
    {
        Console.Write(" {0}", i);
    }
    Console.WriteLine(" }");
}

/* This example produces output similar to the following:
* Numbers contains 10 elements: { 0 1 2 3 4 5 6 7 8 9 }
* Numbers contains 0 elements: { }
*/
Imports System.Collections.Generic

Class Program

    Shared Sub Main()

        Dim Numbers As HashSet(Of Integer) = New HashSet(Of Integer)()

        For i As Integer = 0 To 9
            Numbers.Add(i)
        Next i

        Console.Write("Numbers contains {0} elements: ", Numbers.Count)
        DisplaySet(Numbers)

        Numbers.Clear()
        Numbers.TrimExcess()

        Console.Write("Numbers contains {0} elements: ", Numbers.Count)
        DisplaySet(Numbers)

    End Sub
    ' This code example produces output similar to the following:
    ' Numbers contains 10 elements: { 0 1 2 3 4 5 6 7 8 9 }
    ' Numbers contains 0 elements: { }

    Private Shared Sub DisplaySet(ByVal coll As HashSet(Of Integer))
        Console.Write("{")
        For Each i As Integer In coll
            Console.Write(" {0}", i)
        Next i
        Console.WriteLine(" }")
    End Sub

End Class

注解

Count 设置为零,并且也会释放对集合元素中其他对象的引用。 在调用 TrimExcess 之前,容量保持不变。

此方法是 O (n) 操作,其中 nCount

适用于