开发者

C# Indexer properties - Any way to virtualize the get and not the set method?

I have a special type of dictionary. I'm not sure how to do this exactly, but I'm looking to make the get method virtual, but not the set method:

    public TValue this[TKey key]
    {
  开发者_StackOverflow      get { ... }
        set { ... }
    }

Is it possible and if so what is the correct combination?


You can't do that directly - you would need to add a separate method:

protected virtual TValue GetValue(TKey key) { ...}

public TValue this[TKey key]
{
    get { return GetValue(key); }
    set { ... }
}


Sorry... There is no syntax for doing this in C#, but you can do this instead.

public TValue this[TKey key]
{
   get { return GetValue(key) }
   set { ... }
} 

protected virtual TValue GetValue(TKey key)
{
   ...
}


I might be misunderstanding something but if your Dictionary is going to be readonly you have to implement a wrapper to ensure it is really readony (the dictionary's indexed property is not virtual so you can't override its behavior) in which case you can do the following:

public class ReadOnlyDictionary<TKey, TValue>
{
    Dictionary<TKey, TValue> innerDictionary;

    public virtual TValue this[TKey key]
    {
        get
        {
            return innerDictionary[key];
        }
        private set
        {
            innerDictionary[key] = value;
        }
    }
}


I'm assuming what you're trying to do here is create a situation where they have to define how the property is read but not how the property is set?

This strikes me like a bad idea. You could have a setting setting the value of _myVar but the end-developer constructing a getter that that reads _someOtherVar. That said, I don't know what your use case is, so it is very likely I'm missing something.

Regardless, I think this prior question might help: Why is it impossible to override a getter-only property and add a setter?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜