在 C# 中,可以通过继承 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 | 完全自定义行为和逻辑 |
适用场景 | 仅需扩展或增强现有功能 | 需要从零定义完全不同的字典行为 |
总结
- 如果仅需要对 Dictionary
进行简单的增强或扩展,可以选择 继承方法。 - 如果需要完全定制字典行为,例如自定义存储结构或逻辑,应选择 接口实现方法。