属性的访问修饰符;为什么以下不起作用?
我遇到了一个编译器错误,这对我来说不太有意义。我有一个 internal
属性,我想限制它的 set
块,使其只能通过继承使用。我认为这会起作用:
internal bool MyProperty {
get { return someValue; }
protected internal set { someValue = value; }
}
但编译器说 set
块上的访问修饰符需要比 internal
更具限制性 - 我是否遗漏了某些内容,或者是 protected inside
不比internal
限制更多吗?
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 someValue; }
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
受保护的内部
限制较少;它是受保护的或内部(不是和) - 因此另外允许来自其他程序集的子类访问它。您需要反转:这将允许程序集中的代码以及其他程序集中的子类获取它(读取) - 但只有程序集中的代码可以设置它(写)。
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: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).
来自 C# 中访问修饰符的文档:
为了达到预期的效果,您需要交换访问修饰符,如下所示:
From the documentation on Access Modifiers in C#:
To achieve the desired effect, you instead need to swap the access modifiers, like so:
不,这是两者的并集,而不是交集;因此,受保护的内部限制比这两个单独的限制要少。交集不是 C# 的功能; CLR 确实支持“Family AND Assembly”,但 C# 只支持“Family OR Assembly”。
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".在这里,
受保护的内部
比内部
限制更少。受保护的内部
- 当前程序集以及在其他程序集中继承此类型的任何类型的公共。internal
- 此程序集公共,其他程序集私有Here,
protected internal
is less restrictive thatinternal
.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