简体   繁体   中英

Understanding private set accessors

if i have a struct

struct S
{
    int I;
}

and in my class I have an accessor like this:

class C
{
    public S MyStruct {get; private set;}
}

does that mean that I can still modify the values of the struct outside of class C? Could I do EDIT: made a mistake here:

C MyClass = new C();
C.S.I = 5;

or are the members of the struct still protected by the private modifier?

A private setter only allows access from within the class.

Example:

struct MyStruct { public int I; }
class MyClass { public MyStruct S {get; private set;} }
MyClass C = new MyClass();
C.S = new MyStruct(); // not allowed as private setter

When you access a member of MyStruct like with SI you have to differentiate between class and struct! If MyStruct is a class you will be able to change its value and affect the member variables of S . If it is a struct you can not change the value, as SI gives you a copy.

Example (using definitions above):

C.S.I = 5; // not allowed as MyStruct is a struct

However this is allowed:

class MyStruct { public int I; } // it is a class now!
class MyClass { public MyStruct S {get; private set;} }
MyClass C = new MyClass();
C.S.I = 5; // allowed even though setter for S is private

The property getter will return a copy of the structure instance by virtue of the fact that it's a value type so, even though you can set the field value of that copy, you can't assign the copy back to the property so you haven't actually affected the property value. I'm not even sure that the compiler will accept that code for that very reason. As suggested though, you could have just tested it for yourself.

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