Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Khác biệt giữa Dictionary và Hashtable trong C#

Dictionary<TKey, TValue> (generic) nhanh hơn Hashtable (non-generic) nhờ tránh boxing/unboxing và type safety. Hashtable cho phép key null, Dictionary không (trừ khi TKey là nullable).

Hashtable

Lưu trữ cặp khóa/giá trị dựa trên hash code của khóa. Key và value kiểu object.

using System;
using System.Collections;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();
            ht.Add("E001", "Tom");
            ht.Add("E098", "Amit");
            ht.Add("E110", "Jack");

            ICollection key = ht.Keys;
            foreach (string k in key)
                Console.WriteLine(k + ": " + ht[k]);
            Console.ReadKey();
        }
    }
}

Kết quả

E001: Tom
E098: Amit
E110: Jack

Dictionary

Generic, type-safe, hiệu năng tốt hơn.

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        IDictionary dict = new Dictionary();
        dict.Add(1, 234); dict.Add(2, 489); dict.Add(3, 599);
        dict.Add(4, 798); dict.Add(5, 810); dict.Add(6, 897); dict.Add(7, 909);
        Console.WriteLine("Số phần tử Dictionary: " + dict.Count);
    }
}

Kết quả

Số phần tử Dictionary: 7

Khuyến nghị: Luôn dùng Dictionary<TKey, TValue> cho mã mới. Hashtable chỉ để tương thích ngược.