Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ความแตกต่างระหว่าง Dictionary และ Hashtable ใน C#


ภาพรวม

Dictionary<TKey, TValue> (generic) เร็วกว่าและปลอดภัยกว่า Hashtable (non-generic) สำหรับ strongly-typed collections

Hashtable

  • Non-generic: เก็บ object key และ value
  • ต้อง boxing/unboxing สำหรับ value types
  • ไม่ type-safe - compile time ไม่จับ error ได้
  • Thread-safe สำหรับ single writer / multiple readers (ผ่าน Hashtable.Synchronized)

ตัวอย่าง Hashtable

using System;
using System.Collections;

Hashtable ht = new Hashtable();
ht.Add("E001", "Tom");
ht.Add("E098", "Amit");
ht.Add("E110", "Jack");
foreach (string k in ht.Keys) Console.WriteLine(k + ": " + ht[k]);

Dictionary

  • Generic: Dictionary<TKey, TValue> - type-safe
  • ไม่ต้อง boxing/unboxing
  • ประสิทธิภาพดีกว่า
  • Namespace: System.Collections.Generic
  • ไม่ thread-safe (ใช้ ConcurrentDictionary สำหรับ multi-thread)

ตัวอย่าง Dictionary

using System;
using System.Collections.Generic;

IDictionary dict = new Dictionary();
dict.Add(1, 234); dict.Add(2, 489); dict.Add(3, 599);
Console.WriteLine("Dictionary elements: " + dict.Count);

ตารางเปรียบเทียบ

คุณสมบัติHashtableDictionary<TKey,TValue>
Type Safetyไม่มี (object)มี (Generic)
Boxing/Unboxingต้องใช้ (value types)ไม่ต้องใช้
Performanceช้ากว่าเร็วกว่า
Null Keyอนุญาตไม่อนุญาต (โยน ArgumentNullException)
Key Not Foundคืน nullโยน KeyNotFoundException
Thread Safetyมี Synchronized wrapperไม่มี (ใช้ ConcurrentDictionary)

สรุป

ใช้ Dictionary<TKey, TValue> สำหรับโค้ดใหม่ทุกกรณี ยกเว้นต้องรองรับ legacy code หรือ .NET Framework เก่าที่ไม่มี Generics