覆盖 Dictionary.Add [英] Override Dictionary.Add
问题描述
我需要知道如何覆盖某个静态类中某个字典的添加方法.有什么建议吗?
I need to know how to override the Add-method of a certain Dictionary in a certain static class. Any suggestions?
如果重要的话,字典看起来像这样:
If it matters, the dictionary looks like this:
public static Dictionary<MyEnum,MyArray[]>
有什么建议吗?
推荐答案
您不能覆盖 Dictionary<,>
的 Add
方法,因为它是非虚拟的.您可以通过在派生类中添加具有相同名称/签名的方法来隐藏它,但隐藏与覆盖不同.如果有人转换到基类,他仍然会调用错误的Add
.
You can't override the Add
method of Dictionary<,>
since it's non virtual. You can hide it by adding a method with the same name/signature in the derived class, but hiding isn't the same as overriding. If somebody casts to the base class he will still call the wrong Add
.
正确的做法是创建自己的类,实现IDictionary<,>
(接口),但有一个Dictionary<,>;
(类)而不是成为一个Dictionary<,>
.
The correct way to do this is to create your own class that implements IDictionary<,>
(the interface) but has a Dictionary<,>
(the class) instead of being a Dictionary<,>
.
class MyDictionary<TKey,TValue>:IDictionary<TKey,TValue>
{
private Dictionary<TKey,TValue> backingDictionary;
//Implement the interface here
//Delegating most of the logic to your backingDictionary
...
}
这篇关于覆盖 Dictionary.Add的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!