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

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


方法 1:继承 Dictionary<TKey, TValue>

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

示例代码
using System;
using System.Collections.Generic;

class CustomDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
    // 添加一个新方法,用于显示所有键值对
    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<int, string>();
        customDict.Add(1, "One");
        customDict.Add(2, "Two");
        // customDict.Add(3, null); // 会抛出异常

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

方法 2:实现 IDictionary<TKey, TValue> 接口

通过实现 IDictionary<TKey, TValue> 接口可以完全控制字典的行为。

示例代码
using System;
using System.Collections;
using System.Collections.Generic;

class CustomDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
    private readonly Dictionary<TKey, TValue> _internalDict = new Dictionary<TKey, TValue>();

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

    public ICollection<TKey> Keys => _internalDict.Keys;
    public ICollection<TValue> 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<TKey, TValue> item) => Add(item.Key, item.Value);
    public void Clear() => _internalDict.Clear();
    public bool Contains(KeyValuePair<TKey, TValue> item) => _internalDict.Contains(item);
    public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
    {
        foreach (var pair in _internalDict)
        {
            array[arrayIndex++] = pair;
        }
    }
    public bool Remove(KeyValuePair<TKey, TValue> item) => _internalDict.Remove(item.Key);

    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() => _internalDict.GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => _internalDict.GetEnumerator();
}

class Program
{
    static void Main()
    {
        var customDict = new CustomDictionary<string, int>();
        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<TKey, TValue>实现 IDictionary<TKey, TValue>
开发复杂度较低,直接继承后扩展功能较高,需要实现所有接口成员
灵活性受限于基类 Dictionary<TKey, TValue> 的设计完全自定义行为和逻辑
适用场景仅需扩展或增强现有功能需要从零定义完全不同的字典行为

总结

  1. 如果仅需要对 Dictionary<TKey, TValue> 进行简单的增强或扩展,可以选择 继承方法
  2. 如果需要完全定制字典行为,例如自定义存储结构或逻辑,应选择 接口实现方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

面试八股文

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值