Different access modifiers of properties in C#
Can we have different access modifier for get
and set
in a property开发者_运维技巧?
Yes, you can, however it is subject to the rule that your getter/setter cannot have a less restricted access modifier than the property itself.
For example (C#):
public Foo { get; private set; } //this is okay
protected Bar { get; public set; } //this will throw a compile error
You can restrict the getter or setter of a property:
public string MyProperty
{
get { return _myProperty; }
private set { _myProperty = value; }
}
It also works with internal and protected. However, the key word here is "restrict" - you can't make either modifier more accessible than the overall modifier.
精彩评论