KeyValuePair是單個的鍵值對對象。KeyValuePair可用於接收combox選定的值。
例如:KeyValuePair<string, object> par = (KeyValuePair<string, object>)shoplistcomboBox.SelectedItem;
單線程程序中推薦使用 Dictionary, 有泛型優勢, 且讀取速度較快, 容量利用更充分。
Hashtable是一個集合。在多線程程序中推薦使用 Hashtable, 默認的 Hashtable 允許單線程寫入, 多線程讀取, 對 Hashtable 進一步調用 Synchronized() 方法可以獲得完全線程安全的類型. 而 Dictionary 非線程安全, 必須人為使用 lock 語句進行保護, 效率大減。
1.鍵值對Dictionary:Dictionary<string,string>鍵值對的使用
public void CreateDictionary() { Dictionary<string,string> dic=new Dictionary<string,string>(); //添加 dic.Add("1","one"); dic.Add("2","two"); //取值 string getone=dic["1"]; }
2.鍵值對KeyValuePair:KeyValuePair<string,string>
因為KeyValuePair是單個的鍵值對對象,可以用來遍歷Dictionary字典,或保存combox選擇的值。
public void usekeyvaluepair() { foreach (KeyValuePair<string, string> item in dic) { string a = item.Key; string b = item.Value; } }
3.哈希集合Hashtable
Hashtable是非泛型集合,所以在檢索和存儲值類型時通常會發生裝箱與拆箱的操作。
public void CreateHashtable() { Hashtable hs = new Hashtable(); hs.Add(1,"one"); hs.Add("2","two"); string a=hs[1].ToString(); string b = hs["2"].ToString(); }
Hashtable集合補充:遍歷集合,可使用DictionaryEntry類(定義可設置或檢索的鍵值對)
Hashtable hs = new Hashtable(); hs.Add(1, "one"); hs.Add("2", "two"); foreach (DictionaryEntry item in hs) { string a = item.Key.ToString(); string b = item.Value.ToString(); }
使用foreach遍歷是不能修改值的,只能讀取值,迭代變量相當於一個局部只讀變量。可使用for循環修改。