C# 中清除 Hashtable


使用 C# 中的 Clear() 方法來清除 Hashtable。

以下是我們準備的 Hashtable −

Hashtable h = new Hashtable();
h.Add(1, "Amit");
h.Add(2, "Sachin");
h.Add(3, "Rahul");

使用 clear 方法。

h.Clear();

如果你現在嘗試顯示這個 Hashtable,則不會顯示任何內容,因為 Hashtable 為空。

示例

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main() {
      Hashtable h = new Hashtable();
      h.Add(1, "Amit");
      h.Add(2, "Sachin");
      h.Add(3, "Rahul");
      Console.WriteLine("Keys and Values list:");
      foreach (var key in h.Keys ) {
         Console.WriteLine("Key = {0}, Value = {1}",key , h[key]);
      }
      // clear all key value pairs
      Console.WriteLine("The Hashtable key and Value Pairs are empty now...");
      h.Clear();
      foreach (var key in h.Keys ) {
         Console.WriteLine("Key = {0}, Value = {1}",key , h[key]);
      }
   }
}

輸出

Keys and Values list:
Key = 3, Value = Rahul
Key = 2, Value = Sachin
Key = 1, Value = Amit
The Hashtable key and Value Pairs are empty now...

更新時間: 2020 年 6 月 23 日

401 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.