Hashtable类表示键和值对的集合,这些键和值对是根据键的哈希码进行组织的。该键用于访问集合中的项目。 Hashtable.Clear方法用于从Hashtable中删除所有元素。
句法:
myTable.Clear()
在这里, myTable是哈希表的名称。
例外:如果Hashtable是只读的,则此方法将提供NotSupportedException。
例子:
// C# code to remove all elements
// from the Hashtable
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a Hashtable
Hashtable myTable = new Hashtable();
// Adding elements in Hashtable
myTable.Add("2", "Even & Prime");
myTable.Add("3", "Odd & Prime");
myTable.Add("4", "Even & non-prime");
myTable.Add("9", "Odd & non-prime");
// Print the number of entries in Hashtable
Console.WriteLine("Total number of entries in Hashtable : "
+ myTable.Count);
// To remove all elements from Hashtable
myTable.Clear();
// Print the number of entries in Hashtable
Console.WriteLine("Total number of entries in Hashtable : "
+ myTable.Count);
// Adding elements in Hashtable
myTable.Add("g", "geeks");
myTable.Add("c", "c++");
myTable.Add("d", "data structures");
// Print the number of entries in Hashtable
Console.WriteLine("Total number of entries in Hashtable : "
+ myTable.Count);
// To remove all elements from Hashtable
myTable.Clear();
// Print the number of entries in Hashtable
Console.WriteLine("Total number of entries in Hashtable : "
+ myTable.Count);
}
}
输出:
Total number of entries in Hashtable : 4
Total number of entries in Hashtable : 0
Total number of entries in Hashtable : 3
Total number of entries in Hashtable : 0
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.hashtable.clear?view=netframework-4.7.2