What does the “private” modifier do?

前端 未结 13 1082
予麋鹿
予麋鹿 2021-01-17 07:24

Considering \"private\" is the default access modifier for class Members, why is the keyword even needed?

13条回答
  •  甜味超标
    2021-01-17 07:58

    As pointed out by Jon Skeet in his book C# In Depth, there is one place in C# where the private keyword is required to achieve an effect.

    If my memory serves correctly, the private keyword is the only way to create a privately scoped property getter or setter, when its opposite has greater than private accessibility. Example:

    public bool CanAccessTheMissileCodes
    {
        get { return canAccessTheMissileCodes; }
        private set { canAccessTheMissileCodes = value; }
    }
    

    The private keyword is required to achieve this, because an additional property accessability modifier can only narrow the scope, not widen it. (Otherwise, one might have been able to create a private (by default) property and then add a public modifier.)

提交回复
热议问题