C# 泛型Dictionary (Hashtable)using System;using System.Collections.Generic;public class Example{ public static void Main() { //建立泛型雜湊表,然後加入元素 Dictionary<string, string> oscar = new Dictionary<string, string>(); oscar.Add("哈莉•貝瑞", "《死囚之舞》"); oscar.Add("朱迪•丹奇", "《攜手人生》"); oscar.Add("尼科爾•基德曼", "《紅磨坊》"); oscar.Add("詹妮弗•康納利", "《美麗心靈》"); oscar.Add("蕾妮•齊維格", "《BJ單身日記》"); //刪除元素 oscar.Remove("詹妮弗•康納利"); //假如不存在元素則加入元素 if (!oscar.ContainsKey("茜茜•斯派克")) oscar.Add("茜茜•斯派克", "《不倫之戀》"); //顯然容量和元素個數 Console.WriteLine("元素個數: {0}", oscar.Count); //遍曆集合 Console.WriteLine("74屆奧斯卡最佳女主角及其電影:"); foreach (KeyValuePair<string, string> kvp in oscar) { Console.WriteLine("姓名:{0},電影:{1}", kvp.Key, kvp.Value); } //得到雜湊表中鍵的集合 Dictionary<string, string>.KeyCollection keyColl = oscar.Keys; //遍曆鍵的集合 Console.WriteLine("最佳女主角:"); foreach (string s in keyColl) { Console.WriteLine(s); } //得到雜湊表值的集合 Dictionary<string, string>.ValueCollection valueColl = oscar.Values; //遍曆值的集合 Console.WriteLine("最佳女主角電影:"); foreach (string s in valueColl) { Console.WriteLine(s); } //使用TryGetValue方法擷取指定鍵對應的值 string slove = string.Empty; if (oscar.TryGetValue("朱迪•丹奇", out slove)) Console.WriteLine("我最喜歡朱迪•丹奇的電影{0}", slove); else Console.WriteLine("沒找到朱迪•丹奇的電影"); //清空雜湊表 oscar.Clear(); Console.ReadLine(); }}運行效果如下: