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 implem开发者_JAVA百科ent 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.
精彩评论