Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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[]>

Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
225 views
Welcome To Ask or Share your Answers For Others

1 Answer

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<TKey,TValue>:IDictionary<TKey,TValue>
{
  private Dictionary<TKey,TValue> backingDictionary;

  //Implement the interface here
  //Delegating most of the logic to your backingDictionary
  ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...