Hashtable 簡介
- 命名空間:
System.Collections
- 鍵值對集合,Key 區分大小寫、可快速查找
- Key/Value 均為
object,支援任意型別
基本操作
Hashtable ht = new Hashtable();
// 新增
ht.Add("E", "e");
ht.Add("A", "a");
ht.Add("C", "c");
ht.Add("B", "b");
// 讀取
string val = (string)ht["A"]; // "a"
// 判斷 Key 是否存在
if (ht.Contains("E")) Console.WriteLine("Key E 存在");
// 移除單一 Key
ht.Remove("C");
// 移除所有
ht.Clear();
// 存取已清除的 Key 無輸出
Console.WriteLine(ht["A"]); // 無輸出
注意事項
- Key 不可為 null,Value 可為 null
- Key 重複呼叫
Add 會拋出例外,建議用索引器 ht[key] = value 覆蓋
- 非泛型集合,取值需轉型