Hashtable 為非泛型集合,存放值型別鍵/值會導致裝箱/拆箱,嚴重影響效能。Dictionary<TKey, TValue> 以泛型實現型別安全、零裝箱、高效查找。本文對比兩者程式碼,詳細說明遷移步驟與注意事項。
public static void UseNonGenericHashtable()
{
var numbers = new Hashtable();
numbers.Add(1, "one"); // 鍵裝箱
numbers.Add(2, "two"); // 鍵裝箱
foreach (DictionaryEntry de in numbers) // 拆箱
{
Console.WriteLine($"Key: {de.Key}\tValue: {de.Value}");
}
numbers.Clear();
}
public static void UseGenericDictionary()
{
var numbers = new Dictionary<int, string>();
numbers.Add(1, "one"); // 無裝箱
numbers.Add(2, "two");
foreach (var kvp in numbers) // 強型別列舉
{
Console.WriteLine($"Key: {kvp.Key}\tValue: {kvp.Value}");
}
numbers.Clear();
}
| 面向 | Hashtable | Dictionary<T,U> |
|---|---|---|
| 鍵/值型別 | object | 強型別 TKey/TValue |
| 值型別存取 | 裝箱/拆箱 | 零裝箱 |
| 列舉器型別 | DictionaryEntry | KeyValuePair<T,U> |
| 型別安全 | 編譯期不檢查 | 編譯期強制檢查 |
| ICloneable | 實作 | 未實作(用建構子複製) |
| 同步包裝 | Synchronized() | 無(改用 lock) |
new Dictionary<T,U>(existingDict)lock(dict) { ... } 或專用 _syncRoot 物件Dictionary 可序列化,自訂 IComparer 需 [Serializable]ContainsKey+ItemDictionary 建構子可傳入 IEqualityComparer<TKey>,Hashtable 用 IHashCodeProvider+IComparer參考上一篇「Hashtable 遷移至 Dictionary 完全指南」之核心成員對照表。
將 Hashtable 替換為 Dictionary<TKey, TValue> 是提升 .NET 應用效能與可維護性的最直接手段。遷移成本極低(單純型別參數化),收益顯著:消除裝箱/拆箱、編譯期型別安全、更豐富 API(TryGetValue)。所有新專案與現有專案重構均應優先執行此遷移。