开发者

Asymmetric Accessor Accessibility (C#) -- why?

开发者 https://www.devze.com 2023-03-31 19:31 出处:网络
According to this page in MSDN, turns out that the accessibility of a specific accessor has to be more restrictive than the indexer and that the property it开发者_Python百科self.

According to this page in MSDN, turns out that the accessibility of a specific accessor has to be more restrictive than the indexer and that the property it开发者_Python百科self.

Now, I understand what it means and several other cases (see questions like C# - Improving encapsulation of property in this example?, ERROR: the accessibility modifier of the set accessor must be more restrictive than the property or indexer and Why is internal protected not more restrictive than internal?).

What I'm failing to understand (and it is the question here) is... is there any reason why this is enforced?

It is just not obvious to me what's wrong with having something like this:

// THIS IS WRONG -- I want this to be set by this class and its derivated
protected MyPropertyType MyProperty 
{ 
    get; // this is protected, by the accessibility of the property
    protected set; // this is wrong -- why?
}

I think this is the kind of question where the answer may be so obvious that I'll feel really dumb once I get the answer... but I just couldn't find it around and just cannot get it myself. So... fire at will!


What I'm failing to understand (and it is the question here) is... is there any reason why this is enforced?

I suspect this is for clarity. Your syntax:

protected MyPropertyType MyProperty 
{ 
    get;
    protected set;
}

Would, effectively, be the same as not specifying the accessibility of the setter, ie:

protected MyPropertyType MyProperty 
{ 
    get;
    set;
}

However, when looking at the code, it appears that you were intending to restrict the accessibility. Having the compiler enforce that a specific accessor require more restrictive accessibility likely reduces the overall number of bugs by forcefully simplifying the code by reducing the redundancy.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号