Why don't you use protected
?
public string MyProperty { get; protected set; }
A protected member is accessible within its class and by derived class instances.
Pregunta
Is it possible to give private access to a base class setter and only have it available from the inheriting classes, in the same way as the protected keyword works?
public class MyDerivedClass : MyBaseClass
{
public MyDerivedClass()
{
// Want to allow MyProperty to be set from this class but not
// set publically
public MyProperty = "abc";
}
}
public class MyBaseClass
{
public string MyProperty { get; private set; }
}
Solución
Why don't you use protected
?
public string MyProperty { get; protected set; }
A protected member is accessible within its class and by derived class instances.
Otros consejos
You only need to make the setter as protected like:
public class MyDerivedClass : MyBaseClass
{
public MyDerivedClass()
{
// Want to allow MyProperty to be set from this class but not
// set publically
MyProperty = "abc";
}
}
public class MyBaseClass
{
public string MyProperty { get; protected set; }
}
See also Access Modifiers (C# Reference)
Use protected instead of private.
Protected is the right approach, but for the sake of discussion, it's possible to set a private property this way:
public class MyDerivedClass : MyBaseClass
{
public MyDerivedClass() : base(myProperty: "abc") { }
}
public class MyBaseClass
{
public string MyProperty { get; private set; }
public MyBaseClass(string myProperty) {
this.MyProperty = myProperty;
}
}