Access modifiers on properties; why doesn't the following work?
I've run into a compiler error that doesn't quite make sense to me. I have an internal
property and I want to restrict its set
block such that it is only available through inheritance. I thought this would work:
internal bool MyProperty {
get { return someVa开发者_如何学Pythonlue; }
protected internal set { someValue = value; }
}
But the compiler says that the access modifier on the set
block needs to be more restrictive than internal
- am I missing something, or is protected internal
not more restrictive than internal
?
protected internal
is less restrictive; it is protected or internal (not and) - which therefore additionally allows subclasses from other assemblies to access it. You would need to invert:
protected internal bool MyProperty {
get { return someValue; }
internal set { someValue = value; }
}
This will allow code in your assembly, plus subclasses from other assemblies, get it (read) - but only code in your assembly can set it (write).
From the documentation on Access Modifiers in C#:
The protected internal accessibility level means protected OR internal, not protected AND internal. In other words, a protected internal member can be accessed from any class in the same assembly, including derived classes. To limit accessibility to only derived classes in the same assembly, declare the class itself internal, and declare its members as protected.
To achieve the desired effect, you instead need to swap the access modifiers, like so:
protected internal bool MyProperty
{
get { return someValue; }
internal set { someValue = value; }
}
No, it's the union of the two, not the intersection; hence protected internal
is less restrictive than both of those individually. The intersection isn't a feature of C#; the CLR does support "Family AND Assembly", but C# only supports "Family OR Assembly".
Here, protected internal
is less restrictive that internal
.
protected internal
- public for current assembly and any type that inherits this type in other assemblies.internal
- public for this assembly and private for other assemblies
精彩评论