C# - 改进本例中属性的封装?
我知道错误“设置访问器的可访问性修饰符必须比属性或索引器更具限制性”。我也知道解决办法。只是不是在这个非常具体的情况下。
考虑这个例子:
internal virtual bool IsFocused
{
get
{
return isFocused;
}
protected set
{
isFocused = value;
}
}
private bool isFocused;
它显示了错误。我只是不知道为什么。 “受保护”如何不比内部更难访问?这个问题的解决方案是什么?我尝试将“内部保护”改为“内部保护”,但没有运气。
I know of the error "The accessibility modifier of the set accessor must be more restrictive than the property or indexer". I also know the solution. Just not in this very specific case.
Consider this example:
internal virtual bool IsFocused
{
get
{
return isFocused;
}
protected set
{
isFocused = value;
}
}
private bool isFocused;
It shows the error. I just don't know why. How is "protected" not less accessible than internal? What would be the solution to this problem? I tried putting "internal protected" instead, without luck.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
事实证明,
protected
比internal
更易访问。回想一下,internal
表示“在此程序集之外不可见”(除非通过InternalsVisibleTo
访问,这使得internal
看起来像public
),而protected
表示对所有子类可见。As it turns out,
protected
is more accessible thaninternal
. Recall thatinternal
means "not visible outside of this assembly" (except throughInternalsVisibleTo
access, which makesinternal
look likepublic
), whereasprotected
means visible to all subclasses.@bobbymcr 他的分析完全正确。解决方案是将属性标记为
内部受保护
。在 C# 中,这意味着派生类和当前程序集中的所有类都可以访问它。如果将
internal protected
放入访问器方法 - 这意味着派生类可以访问它。但整个财产不是,这会导致错误。如果您将整个属性标记为内部受保护
并将访问器方法标记为受保护
- 一切都很好。另一种选择是引入将在 setter 中调用的
protected
方法。然后,您可以将整个属性标记为internal
并允许仅覆盖该方法。@bobbymcr is entirely right in his analysis. The solution would be to mark property as
internal protected
. In C# that means that it would be accessible both to derived classes AND to all classes from current assembly.If you put
internal protected
to accessor method - that means that it is accessible to derived classes. But entire property is not, which causes the error. If you mark entire property asinternal protected
and accessor method asprotected
- everything is fine.Other option would be to introduce
protected
method that would be called in setter. Then you could mark entire property asinternal
and allow to override only that method.protected
允许继承类访问它,而internal
则不允许 -internal
限制对程序集本身的访问 - 请参阅 http://msdn.microsoft.com/en-us/library/7c5ka91b%28v=vs.80%29.aspxprotected
allows an inherting class to access it whileinternal
does NOT -internal
restricts access to the assembly itself - see http://msdn.microsoft.com/en-us/library/7c5ka91b%28v=vs.80%29.aspx