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


Two options:

  • Make the property internal (not a class) and group the classes into different assemblies.
  • Use the magic of reflection.


Unfortunately there are no classes in C # friend

.

+2


source


Within the current assembly, you can make it internal

.

Outside the current assembly, it is best to make it available to specific assemblies via [InternalsVisibleTo]

.



.NET does not offer more granular friend access.

+8


source


class Person : IReadOnlyPerson {
    public string Name { get; set; }
}

public interface IReadOnlyPerson {
    string Name { get; }
}

      

For those classes that need to access r / o - use IReadOlyPerson

+7


source


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


source







All Articles