建立 C# 中的 Hashtable 同步包裝器


要建立 Hashtable 的同步包裝器,程式碼如下 −

示例

 線上示例

using System;
using System.Collections;
public class Demo {
   public static void Main() {
      Hashtable hash = new Hashtable();
      hash.Add("1", "AB");
      hash.Add("2", "CD");
      hash.Add("3", "EF");
      hash.Add("4", "GH");
      hash.Add("5", "IJ");
      hash.Add("6", "KL");
      Console.WriteLine("Hashtable elements...");
      foreach(DictionaryEntry d in hash) {
         Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value);
      }
      Console.WriteLine("Hashtable is synchronized? = "+hash.IsSynchronized);
   }
}

輸出

這將生成以下輸出 −

Hashtable elements...
Key = 1, Value = AB
Key = 2, Value = CD
Key = 3, Value = EF
Key = 4, Value = GH
Key = 5, Value = IJ
Key = 6, Value = KL
Hashtable is synchronized? = False

示例

我們來看另一個示例 −

 線上示例

using System;
using System.Collections;
public class Demo {
   public static void Main() {
      Hashtable hash = new Hashtable();
      hash.Add("1", "Mark");
      hash.Add("2", "Gary");
      hash.Add("3", "Jacob");
      hash.Add("4", "Andy");
      hash.Add("5", "Jack");
      Console.WriteLine("Hashtable elements...");
      foreach(DictionaryEntry d in hash) {
         Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value);
      }
      Console.WriteLine("Hashtable is synchronized? = "+hash.IsSynchronized);
      Hashtable hash2 = Hashtable.Synchronized(hash);
      Console.WriteLine("Hashtable is synchronized? = "+hash2.IsSynchronized);
   }
}

輸出

這將生成以下輸出 −

Hashtable elements...
Key = 1, Value = Mark
Key = 2, Value = Gary
Key = 3, Value = Jacob
Key = 4, Value = Andy
Key = 5, Value = Jack
Hashtable is synchronized? = False
Hashtable is synchronized? = True

更新於: 2019 年 12 月 6 日

78 次瀏覽

開啟你的 職業

完成課程以獲取認證

開始
廣告