C# - Improving encapsulation of property in this e

2020-02-10 22:16发布

问题:

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.

回答1:

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



回答2:

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.



回答3:

@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.