我需要知道如何覆盖一定字典的加载方法在一定的静态类。有什么建议?
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[]>
有什么建议?
您不能覆盖添加
词典&LT的方法;,&GT;
,因为它是不虚。您可以通过添加一个方法具有相同名称/签名在派生类中隐藏它,但隐藏是不一样的压倒一切的。如果有人强制转换为基类,他仍然会叫错添加
。
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&LT;,&GT;
(界面),但的的一个词典&LT;,&GT;
(类)来代替的是的一个词典&LT;,&GT;
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
...
}