在C#中,如何实现自定义的Dictionary类型?

在C#中,如何实现自定义的Dictionary类型?

编码文章call10242025-02-11 11:31:349A+A-

在 C# 中,可以通过继承 Dictionary 类或实现 IDictionary 接口来自定义一个 Dictionary 类型。下面分别介绍这两种方法的实现方式。


方法 1:继承Dictionary

继承基类 Dictionary,并在此基础上添加新的功能或重写现有方法。

示例代码

using System;
using System.Collections.Generic;

class CustomDictionary : Dictionary
{
    // 添加一个新方法,用于显示所有键值对
    public void DisplayAll()
    {
        foreach (var kvp in this)
        {
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
        }
    }

    // 重写添加方法,确保值不能为null
    public new void Add(TKey key, TValue value)
    {
        if (value == null)
        {
            throw new ArgumentNullException(nameof(value), "Value cannot be null");
        }
        base.Add(key, value);
    }
}

class Program
{
    static void Main()
    {
        var customDict = new CustomDictionary();
        customDict.Add(1, "One");
        customDict.Add(2, "Two");
        // customDict.Add(3, null); // 会抛出异常

        Console.WriteLine("Custom Dictionary Content:");
        customDict.DisplayAll();
    }
}

方法 2:实现IDictionary接口

通过实现 IDictionary 接口可以完全控制字典的行为。

示例代码

using System;
using System.Collections;
using System.Collections.Generic;

class CustomDictionary : IDictionary
{
    private readonly Dictionary _internalDict = new Dictionary();

    // 实现 IDictionary 的成员
    public TValue this[TKey key]
    {
        get => _internalDict[key];
        set => _internalDict[key] = value;
    }

    public ICollection Keys => _internalDict.Keys;
    public ICollection Values => _internalDict.Values;
    public int Count => _internalDict.Count;
    public bool IsReadOnly => false;

    public void Add(TKey key, TValue value)
    {
        if (_internalDict.ContainsKey(key))
        {
            throw new ArgumentException("Duplicate keys are not allowed.");
        }
        _internalDict.Add(key, value);
    }

    public bool ContainsKey(TKey key) => _internalDict.ContainsKey(key);
    public bool Remove(TKey key) => _internalDict.Remove(key);
    public bool TryGetValue(TKey key, out TValue value) => _internalDict.TryGetValue(key, out value);

    public void Add(KeyValuePair item) => Add(item.Key, item.Value);
    public void Clear() => _internalDict.Clear();
    public bool Contains(KeyValuePair item) => _internalDict.Contains(item);
    public void CopyTo(KeyValuePair[] array, int arrayIndex)
    {
        foreach (var pair in _internalDict)
        {
            array[arrayIndex++] = pair;
        }
    }
    public bool Remove(KeyValuePair item) => _internalDict.Remove(item.Key);

    public IEnumerator> GetEnumerator() => _internalDict.GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => _internalDict.GetEnumerator();
}

class Program
{
    static void Main()
    {
        var customDict = new CustomDictionary();
        customDict.Add("A", 1);
        customDict.Add("B", 2);

        Console.WriteLine("Custom Dictionary Content:");
        foreach (var item in customDict)
        {
            Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
        }
    }
}

两种方法的比较

特性

继承 Dictionary

实现 IDictionary

开发复杂度

较低,直接继承后扩展功能

较高,需要实现所有接口成员

灵活性

受限于基类 Dictionary 的设计

完全自定义行为和逻辑

适用场景

仅需扩展或增强现有功能

需要从零定义完全不同的字典行为


总结

  1. 如果仅需要对 Dictionary 进行简单的增强或扩展,可以选择 继承方法
  2. 如果需要完全定制字典行为,例如自定义存储结构或逻辑,应选择 接口实现方法
点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4