Hashtable (System.Collections) 為非泛型鍵值對集合,基於雜湊表演算法實現,提供近似 O(1) 的新增、刪除、查找效能。鍵值皆為 object 型別,需自行處理型別轉換與 Boxing/Unboxing 開銷。.NET 2.0+ 建議改用泛型 Dictionary<TKey, TValue> 獲得型別安全與效能提升。
GetHashCode() 取得 32-bit 整數hashCode & (bucketCount - 1) (桶數為 2 的冪次)Equals() 確認鍵相等var ht = new Hashtable();
// 新增/更新
ht["name"] = "Alice";
ht["age"] = 30;
ht.Add("city", "Taipei"); // 鍵重複拋例外
// 查找
if (ht.ContainsKey("name")) {
string name = (string)ht["name"]; // 需轉型
}
// 刪除
ht.Remove("age");
ht.Clear();
// 列舉
foreach (DictionaryEntry entry in ht) {
Console.WriteLine($"{entry.Key} = {entry.Value}");
}
// 同步包裝 (Thread-safe wrapper)
var syncHt = Hashtable.Synchronized(new Hashtable());
| 項目 | Hashtable | Dictionary<TKey,TValue> |
|---|---|---|
| 型別安全 | 否 (object) | 是 (泛型) |
| Boxing 開銷 | 有 (實值型別) | 無 |
| 序列化 | 支援 ISerializable | 支援 |
| 多執行緒 | Synchronized() 包裝 | 需自行鎖定或用 ConcurrentDictionary |
| 效能 (實值型別) | 基準 | 快 2-3 倍 |
new Dictionary(capacity) 減少擴容次數。ConcurrentDictionary 或 ImmutableDictionary。






