What does the “private” modifier do?

前端 未结 13 968
予麋鹿
予麋鹿 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:56

    Using private explicitly signals your intention and leaves clues for others who will support your code ;)

    0 讨论(0)
  • 2021-01-17 07:57

    Actually, if the class or struct is not declared with an access modifier it defaults to internal.

    So if you want to make it private, use private.

    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2021-01-17 07:58

    Some coding styles recommend that you put all the "public" items first, followed by the "private" items. Without a "private" keyword, you couldn't do it that way around.

    Update: I didn't notice the "c#" tag on this so my answer applies more to C++ than to C#.

    0 讨论(0)
  • 2021-01-17 07:59

    The private modifier explains intent.

    A private member variable is not intended for direct manipulation outside the class. get/set accessors may or may not be created for the variable.

    A private method is not intended for use outside the class. This may be for internal functionality only. Or you could make a default constructor private to prevent the construction of the class without passing in values.

    The private modifier (and others like it) can be a useful way of writing self documenting code.

    0 讨论(0)
  • 2021-01-17 08:06

    For completenes. And some people actually prefer to be explicit in their code about the access modifiers on their methods.

    0 讨论(0)
提交回复
热议问题