c# virtual dictionary?
I have a class with a dictionary object. Any class that derives from that class, I want to override the dictionary with it's own implementation.
How can this be achieved as the virtual开发者_Go百科 keyword is not valid here?
Thanks.
You can't have virtual fields, but you can have virtual properties.
Additionally, it would be a good idea to declare the property-type to be of the IDictionary<TKey, TValue>
interface rather than the Dictionary<TKey, TValue>
concrete- type, since this class is not designed for inheritance.
E.g:
private readonly Dictionary<string, int> _myDictionary
= new Dictionary<string, int>();
protected virtual IDictionary<string, int> MyDictionary
{
get
{
return _myDictionary;
}
}
Subclasses will not see the field; only the property will be visible. They are free to override the property and provide their own implementation; for example by returning an instance of a custom-type that implements the interface.
Something like this should work:
public class Base
{
private Dictionary<string, string> dictionary = new Dictionary<string, string>();
public virtual IDictionary<string, string> DictInstance
{
get { return this.dictionary; }
}
}
public class Derived : Base
{
private MySpecialDictionary otherDictionary = new MySpecialDictionary();
public override IDictionary<string, string> DictInstance
{
get { return this.otherDictionary; }
}
}
You can make dictionary variable private and serve it via virtual getter. Derived class cannot completely throw inherited member away, only override class functions.
You could declare the field as IDictionary, then each subclass initializes it with a different implementation. Or do as Ani suggest.
精彩评论