Partially encapsulate a C # field
I want to know if there is any pattern that can solve this problem: I have a set of properties that need to be publicly available to multiple classes, and for other classes to be read-only, the classes need to be public .
I don't want to use reflection or other bad performance makers.
I know I can make them RO and implement the logic inside the class, but I don't think that's good.
Any help?
+2
source to share
4 answers
You can try declaring your setters protected in the base class. Any class that outputs it will be able to install it. But any class using a derived class will only see the read-only property.
public class ClassBase
{
public int MyProperty
{
get;
protected set;
}
}
public sealed class ClassDerived : ClassBase
{
public ClassDerived()
{
MyProperty = 4; // will set
}
}
public class ClassUsingDerived
{
public ClassUsingDerived()
{
ClassDerived drv = new ClassDerived();
drv.MyProperty = 5; // will fail
}
}
That is, if I understood the question correctly :)
0
Sergey
source
to share