问题
If I have a class that contains properties with private set and protected set accessibility levels set, will I be able to change those properties on another instance of the same class?
Note: I'm not on a machine which I can test this on right now, otherwise I'd just run the code below.
For instance:
public class Foo
{
public string A {get; private set;}
public string B {get; protected set;}
public void Bar()
{
var someOtherFoo = new Foo();
// Does this change someOtherFoo's A?
someOtherFoo.A = "A";
// Does this change someOtherFoo's B?
someOtherFoo.B = "B";
}
}
回答1:
Yes. The access is to the type, not the instance. This is especially useful for things like implementing equality, as you can test this.x == other.x && this.y == other.y;
. Access is also available to nested types.
回答2:
Short answer : Yes
回答3:
// Does this change someOtherFoo's A? // Does this change someOtherFoo's B?
Yes and yes.
来源:https://stackoverflow.com/questions/2568576/setting-protected-private-properties-from-a-different-instance-of-the-same-class