要为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 中的元素..."); foreach(DictionaryEntry d in hash) { Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value); } Console.WriteLine("哈希表是否已同步? = "+hash.IsSynchronized); } }
输出结果
这将产生以下输出-
Hashtable 中的元素... Key = 1, Value = AB Key = 2, Value = CD Key = 3, Value = EF Key = 4, Value = GH Key = 5, Value = IJ Key = 6, Value = KL 哈希表是否已同步? = 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 中的元素..."); foreach(DictionaryEntry d in hash) { Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value); } Console.WriteLine("哈希表是否已同步? = "+hash.IsSynchronized); Hashtable hash2 = Hashtable.Synchronized(hash); Console.WriteLine("哈希表是否已同步? = "+hash2.IsSynchronized); } }
输出结果
这将产生以下输出-
Hashtable 中的元素... Key = 1, Value = Mark Key = 2, Value = Gary Key = 3, Value = Jacob Key = 4, Value = Andy Key = 5, Value = Jack 哈希表是否已同步? = False 哈希表是否已同步? = True