开发者

Different access modifiers of properties in C#

开发者 https://www.devze.com 2023-03-04 16:48 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号