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

前端 未结 16 2784
盖世英雄少女心
盖世英雄少女心 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 01:52

    A graphical overview (summary in a nutshell)

    Visibility

    Since static classes are sealed, they cannot be inherited (except from Object), so the keyword protected is invalid on static classes.



    For the defaults if you put no access modifier in front, see here:
    Default visibility for C# classes and members (fields, methods, etc.)?

    Non-nested

    enum                              public
    non-nested classes / structs      internal
    interfaces                        internal
    delegates in namespace            internal
    class/struct member(s)            private
    delegates nested in class/struct  private
    

    Nested:

    nested enum      public
    nested interface public
    nested class     private
    nested struct    private
    

    Also, there is they sealed-keyword, which makes a class not-inheritable.
    Also, in VB.NET, the keywords are sometimes different, so here a cheat-sheet:

提交回复
热议问题