简体   繁体   中英

Can separate access modifiers be specified for the get and set accessors of a property?

Can we specify the access modifiers for the get and set accessors of property in C#/.NET?

If so, what would be the best approach to implement this?

Yes, this is possible. It is called Asymmetric Accessor Accessibility, and you can read the MSDN documentation for it on this page . The code would look something like this:

public int Age
{
    get
    {
        return _age;
    }
    protected set
    {
        _age = value;
    }
}

However, there are a couple of important caveats to keep in mind:

  • Only one accessor can be modified.
  • Any restrictions placed on an individual accessor must be more restrictive than the accessibility level of the property itself, not less.
  • You cannot use accessor modifiers on an interface or an explicit implementation of an interface member.

Yes you can...

public class Example
{
    public string Property
    {
        get;
        private set;
    }

    public string Property2
    {
        get;
        protected set;
    }
}

etc.

http://msdn.microsoft.com/en-us/library/ms173121.aspx shows the possible modifiers. If you want to have different modifiers, write:

[Modifier] [DataType] ProperyName{
    [Modifier] get{}
    [Modifier] set{}
}

However if you declare inner modifiers, they must be less or equal visible than the outer ones.

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