简体   繁体   中英

Property access modifiers with setters and getters

I have the following C# code:

class C
{
    public int A { get; private set; }
}

How is the access modifier placed before the property type and name ('public' in this example) related to the specified access modifiers for the getters and setters?

It means that getter of this property is public , but setter is private - you can read this property outside class or assembly, but you can set it only inside the class this property is declared.

If you don't specify modifier for getter or setter then they will have modifier before property name:

protected int Value {get; set;}

It means that you can read and write this property only inside this class or classes that inherit this one - getter and setter have modifier protected .

You can restrict getter or setter of the property for your needs but modifier of getter or setter should be more strict than modifier before property name.

Also, you can't restrict both getter and setter because in this case the modifier before property name will not have some meaning. You can restrict only getter or only setter .

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