C # index properties - Any way to virtualize the get method, not the set method?

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

public TValue this[TKey key] { get { ... } set { ... } } 

Is it possible, and if so, what is the right combination?

+6
source share
4 answers

You cannot do this directly - you will need to add a separate method:

 protected virtual TValue GetValue(TKey key) { ...} public TValue this[TKey key] { get { return GetValue(key); } set { ... } } 
+12
source

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

 public TValue this[TKey key] { get { return GetValue(key) } set { ... } } protected virtual TValue GetValue(TKey key) { ... } 
+6
source

Perhaps I am misunderstanding something, but if your Dictionary is read-only, you should implement a shell to make sure it is really accurate (the property of the indexed dictionary is not virtual, so you cannot override its behavior) in which 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; } } } 
+1
source

I suppose what you are trying to do here is to create a situation where they must determine how the property is read, but not how to set the property?

This seems like a bad idea to me. You may have a parameter specifying the value of _myVar, but the end developer constructs a getter that reads _someOtherVar. However, I do not know what your use case is, so it is very likely that I missed something.

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

0
source

Source: https://habr.com/ru/post/892527/


All Articles