Override Dictionary.Add

前端 未结 5 1906
星月不相逢
星月不相逢 2020-12-17 10:07

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:

5条回答
  •  温柔的废话
    2020-12-17 10:42

    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.

    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:IDictionary
    {
      private Dictionary backingDictionary;
    
      //Implement the interface here
      //Delegating most of the logic to your backingDictionary
      ...
    }
    

提交回复
热议问题