覆盖 Dictionary.Add [英] Override Dictionary.Add

查看:20
本文介绍了覆盖 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆