C# - Improving encapsulation of property in this example?

会有一股神秘感。 提交于 2019-11-29 06:26:42

protected allows an inherting class to access it while internal does NOT - internal restricts access to the assembly itself - see http://msdn.microsoft.com/en-us/library/7c5ka91b%28v=vs.80%29.aspx

As it turns out, protected is more accessible than internal. Recall that internal means "not visible outside of this assembly" (except through InternalsVisibleTo access, which makes internal look like public), whereas protected means visible to all subclasses.

@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 as internal protected and accessor method as protected - everything is fine.

internal protected virtual bool IsFocused
{
    get
    {
        return isFocused;
    }
    protected set
    {
        isFocused = value;
    }
}
private bool isFocused;

Other option would be to introduce protected method that would be called in setter. Then you could mark entire property as internal and allow to override only that method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!