I have a base class and a derived class. Each has the same property which has a private
setter so the value can be set by some logic inside the class.
class First
{
internal virtual int Value { get; private set; }
void SetValue(int toValue)
{
Value = toValue;
}
}
class Second : First
{
internal override int Value { get; private set; }
void SetValue(int toValue)
{
Value = toValue;
}
}
This is resulting in a compiler error:
The property or indexer ... cannot be used in this context because the set accessor is inaccessible.
Why is that the case, and how can I achieve what I'm trying to do? Is this not possible with auto-implemented properties, in other words, do I have to use a backing field instead?
Second
would be unable to set
the value of Value
from First
due to Value
s setter being private
. If you need your subclass to be able to set it, it needs to be protected
in the base.
Getters and Setters are basically methods. You can't override methods you can't see. The virtual
in this case only applies to the getter as virtual private
is not allowable.
It's not just that you can't see it to use it, you cannot override it at all.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.