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

Lấy bản sao chỉ đọc của OrderedDictionary trong C#

Phương thức AsReadOnly() của OrderedDictionary trả về một wrapper chỉ đọc (read-only wrapper) bao bọc OrderedDictionary gốc. Wrapper này ngăn chặn việc thêm, xóa, sửa các phần tử nhưng vẫn cho phép đọc dữ liệu.

Ví dụ 1: Tạo read-only wrapper từ OrderedDictionary

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

public class Demo
{
    public static void Main()
    {
        OrderedDictionary dict1 = new OrderedDictionary();
        dict1.Add("A", "Books");
        dict1.Add("B", "Electronics");
        dict1.Add("C", "Smart Wearables");
        dict1.Add("D", "Pet Supplies");
        dict1.Add("E", "Clothing");
        dict1.Add("F", "Footwear");

        Console.WriteLine("Các phần tử của OrderedDictionary1...");
        foreach (DictionaryEntry d in dict1)
        {
            Console.WriteLine(d.Key + " " + d.Value);
        }

        OrderedDictionary dict2 = new OrderedDictionary();
        dict2.Add("1", "One");
        dict2.Add("2", "Two");
        dict2.Add("3", "Three");
        dict2.Add("4", "Four");
        dict2.Add("5", "Five");
        dict2.Add("6", "Six");

        Console.WriteLine("\nCác phần tử của OrderedDictionary2...");
        foreach (DictionaryEntry d in dict2)
        {
            Console.WriteLine(d.Key + " " + d.Value);
        }

        Console.WriteLine("\nOrderedDictionary1 bằng OrderedDictionary2? = " + dict1.Equals(dict2));

        // Tạo bản sao chỉ đọc
        OrderedDictionary orderedDict = dict2.AsReadOnly();

        Console.WriteLine("OrderedDictionary chỉ đọc? = " + orderedDict.IsReadOnly);
    }
}

Kết quả

Các phần tử của OrderedDictionary1...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear

Các phần tử của OrderedDictionary2...
1 One
2 Two
3 Three
4 Four
5 Five
6 Six
OrderedDictionary1 bằng OrderedDictionary2? = False
OrderedDictionary chỉ đọc? = True

Ví dụ 2: Tạo read-only wrapper trực tiếp

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

public class Demo
{
    public static void Main()
    {
        OrderedDictionary dict = new OrderedDictionary();
        dict.Add("A", "Books");
        dict.Add("B", "Electronics");
        dict.Add("C", "Smart Wearables");
        dict.Add("D", "Pet Supplies");
        dict.Add("E", "Clothing");
        dict.Add("F", "Footwear");

        Console.WriteLine("Các phần tử của OrderedDictionary...");
        foreach (DictionaryEntry d in dict)
        {
            Console.WriteLine(d.Key + " " + d.Value);
        }

        // Tạo bản sao chỉ đọc
        OrderedDictionary orderedDict = dict.AsReadOnly();

        Console.WriteLine("OrderedDictionary chỉ đọc? = " + orderedDict.IsReadOnly);

        // Thử sửa - sẽ ném NotSupportedException
        try
        {
            orderedDict.Add("G", "Test");
        }
        catch (NotSupportedException ex)
        {
            Console.WriteLine("Lỗi: " + ex.Message);
        }
    }
}

Kết quả

Các phần tử của OrderedDictionary...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
OrderedDictionary chỉ đọc? = True
Lỗi: Collection is read-only.

Đặc điểm của AsReadOnly()

Đặc điểm Mô tả
Trả về OrderedDictionary (wrapper)
IsReadOnly true
IsFixedSize true
Dữ liệu gốc Chia sẻ (shallow wrapper)
Thay đổi gốc Ảnh hưởng đến wrapper

Lưu ý quan trọng: Shallow Wrapper

⚠️ Quan trọng: AsReadOnly() tạo một wrapper nông (shallow wrapper), không phải bản sao sâu (deep copy). Thay đổi trên OrderedDictionary gốc SẼ phản ánh lên wrapper chỉ đọc.
OrderedDictionary original = new OrderedDictionary();
original.Add("A", "Apple");

OrderedDictionary readOnly = original.AsReadOnly();
Console.WriteLine(readOnly["A"]); // "Apple"

// Thay đổi original
original["A"] = "Banana";

Console.WriteLine(readOnly["A"]); // "Banana" - THAY ĐỔI ĐƯỢC PHẢN ÁNH!

So sánh với ReadOnlyDictionary<TKey, TValue>

Đặc điểm OrderedDictionary.AsReadOnly() ReadOnlyDictionary<TKey,TValue>
Type-safe Không (object) Có (Generic)
Wrapper behavior Shallow (reflects changes) Shallow (reflects changes)
Interface IDictionary (non-generic) IReadOnlyDictionary<TKey,TValue>
Namespace System.Collections.Specialized System.Collections.ObjectModel

Cách tạo bản sao độc lập (Deep Copy)

// Tạo bản sao thực sự - không liên kết với gốc
OrderedDictionary copy = new OrderedDictionary();
foreach (DictionaryEntry entry in original)
{
    copy.Add(entry.Key, entry.Value);
}

// Bây giờ copy.IsReadOnly = false, có thể sửa tự do
// Thay đổi original không ảnh hưởng copy

Lưu ý

  • OrderedDictionary đã lỗi thời - cân nhắc Dictionary<TKey, TValue> + ReadOnlyDictionary<TKey, TValue>
  • Wrapper chỉ đọc ném NotSupportedException cho Add, Remove, Clear, Indexer set
  • Vẫn cho phép: duyệt, truy xuất key, Contains, Count
  • Namespace: System.Collections.Specialized