简体   繁体   中英

Property with internal set and protected get

I want to do so a variable (let's call it Foo) that can only be modified within the assembly but can be acessed by any child class, even outside the assembly So I want to have an internal set and a protected get:

Doing protected int Foo { internal set; get; } protected int Foo { internal set; get; } protected int Foo { internal set; get; } tells me this that the set must be more restrictive than the property or indexer But internal int Foo { set; protected get; } internal int Foo { set; protected get; } internal int Foo { set; protected get; } tells me the same thing for the get

How can I solve that?

You could create an internal method (or a proxy property) to call set on it.

protected int Foo { private set; get; }

internal void SetFoo(int foo)
{
    Foo = foo;
}

In this case you can set the setter of Foo to private .

Do note that this allows anything in your assembly that has a reference to this object can call SetFoo , which may not be what you want.

Use internal for the setter and protected internal for the whole property.

public class X
{
    // Read from this assembly OR child classes
    // Write from this assembly
    protected internal int Foo { internal set; get; }

}

The name protected internal is a bit misleading, but does what you want to achieve:

A protected internal member is accessible from the current assembly or from types that are derived from the containing class.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/protected-internal

So, because the setter is internal , you can set the property from anywhere in the same assembly but not from a different assembly. And because the property as a whole is protected internal , you can read it from anywhere in the same assembly OR from child classes in any assembly.


Another approach:

public class X
{
    // Read from child classes 
    // Write only from child classes in the same assembly
    protected int Foo { private protected set;  get; }

}

A private protected member is accessible by types derived from the containing class, but only within its containing assembly.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private-protected

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM