In C#, what is the difference between public, private, protected, and having no access modifier?

前端 未结 16 2751
盖世英雄少女心
盖世英雄少女心 2020-11-22 01:12

All my college years I have been using public, and would like to know the difference between public, private, and protected

16条回答
  •  清酒与你
    2020-11-22 02:01

    C# has, in total, 6 access modifiers:

    private: The member declared with this accessibility can be visible within the containing type, it is not visible to any derived types, other types in the same assembly or types outside of the containing assembly. i.e., access is limited to the containing type only.

    protected: The member declared with this accessibility can be visible within the types derived from the containing type within the containing assembly, and the types derived from the containing type outside of the containing assembly. i.e., access is limited to derived types of the containing type.

    internal: The member declared with this accessibility can be visible within the assembly containing this member, it is not visible to any assembly outside of the containing assembly. i.e., access is limited to containing assembly only.

    internal protected: The member declared with this accessibility can be visible within the types derived from the containing type within or outside of the containing assembly, it is also visible to any types within the containing assembly. i.e., access is limited to containing assembly or derived types.

    public: The member declared with this accessibility can be visible within the assembly containing this member, or any other assembly that references the containing assembly. i.e., access is not limited.

    In C# 7.2, a new level of accessibility was added:

    private protected: The member declared with this accessibility can be visible within the types derived from this containing type within the containing assembly. It is not visible to any types not derived from the containing type, or outside of the containing assembly. i.e., the access is limited to derived types within the containing assembly.

    Source including a sample code of the new private protected access modifier

提交回复
热议问题