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

Tạo HybridDictionary case-sensitive với kích thước ban đầu trong C#

Constructor HybridDictionary(int initialSize, bool caseInsensitive) cho phép tạo HybridDictionary với dung lượng ban đầu và cài đặt case-sensitive cho key so sánh chuỗi.

Ví dụ 1: Case-insensitive (mặc định, caseInsensitive = false)

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        // caseInsensitive = false -> CASE SENSITIVE (phân biệt chữ hoa/thường)
        HybridDictionary myDict = new HybridDictionary(5, false);
        
        myDict.Add("A", "AB");
        myDict.Add("B", "BC");
        myDict.Add("C", "DE");
        myDict.Add("D", "FG");
        myDict.Add("e", "fg"); // 'e' khác 'E'

        Console.WriteLine("Các cặp Key/Value (Case Sensitive)...");
        foreach (DictionaryEntry de in myDict)
        {
            Console.WriteLine("Key = " + de.Key + ", Value = " + de.Value);
        }
    }
}

Kết quả

Các cặp Key/Value (Case Sensitive)...
Key = A, Value = AB
Key = B, Value = BC
Key = C, Value = DE
Key = D, Value = FG
Key = e, Value = fg

Ví dụ 2: Case-insensitive (caseInsensitive = true)

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        // caseInsensitive = true -> KHÔNG phân biệt chữ hoa/thường
        HybridDictionary myDict = new HybridDictionary(5, true);
        
        myDict.Add("A", "AB");
        myDict.Add("B", "BC");
        myDict.Add("C", "DE");
        myDict.Add("e", "fg"); // 'e' được coi là trùng 'E'
        myDict.Add("E", "FG"); // LỖI: Key 'E' đã tồn tại (case-insensitive)

        Console.WriteLine("Các cặp Key/Value...");
        foreach (DictionaryEntry de in myDict)
        {
            Console.WriteLine("Key = " + de.Key + ", Value = " + de.Value);
        }
    }
}

Kết quả - Runtime Exception

Run-time exception : An entry with the same key already exists.
Stack Trace: 
[System.ArgumentException: An entry with the same key already exists.]
   at System.Collections.Specialized.ListDictionary.Add(Object key, Object value)
   at System.Collections.Specialized.HybridDictionary.Add(Object key, Object value)
   at Demo.Main() :line 15

Giải thích tham số caseInsensitive

Giá trị Ý nghĩa Ví dụ
true Không phân biệt hoa/thường (Case-insensitive) "A" == "a" -> trùng key
false Phân biệt hoa/thường (Case-sensitive) "A" != "a" -> key khác nhau

Cơ chế nội bộ

  • Khi caseInsensitive = true: Sử dụng CaseInsensitiveComparer / CaseInsensitiveHashCodeProvider
  • Khi caseInsensitive = false: Sử dụng so sánh mặc định (Object.Equals, GetHashCode)
  • Áp dụng cho cả ListDictionary (khi nhỏ) và Hashtable (khi lớn)

So sánh với Dictionary<TKey, TValue> hiện đại

// Dictionary - Case-sensitive (mặc định)
var dict1 = new Dictionary<string, string>();
dict1.Add("A", "AB");
dict1.Add("a", "ab"); // OK - key khác nhau

// Dictionary - Case-insensitive
var dict2 = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
dict2.Add("A", "AB");
dict2.Add("a", "ab"); // ArgumentException - key trùng

// Các StringComparer phổ biến:
// StringComparer.Ordinal              - Case-sensitive, fast
// StringComparer.OrdinalIgnoreCase    - Case-insensitive, fast
// StringComparer.CurrentCulture       - Theo culture hiện tại
// StringComparer.InvariantCulture     - Culture-independent

Lưu ý quan trọng

  • HybridDictionary đã lỗi thời - không dùng cho code mới
  • Không type-safe (key/value là object)
  • Case-insensitive chỉ áp dụng cho key kiểu string
  • Non-string key luôn so sánh case-sensitive (Equals/GetHashCode mặc định)
  • Constructor (int, bool) chỉ ảnh hưởng so sánh key, không ảnh hưởng value

Best Practice hiện nay

// Thay vì HybridDictionary, dùng Dictionary với StringComparer
var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
// Hoặc
var dict = new Dictionary<string, string>(5, StringComparer.OrdinalIgnoreCase); // Với capacity

// Type-safe, hiệu năng tốt, API hiện đại