Nested classes are defined as the name of a class or struct.
class container{ class Nested { Nested () {}} }
<1> The default access permission for nested classes is private and can be specified as public,protected,private,internal,protected internal.
<2> nested types can access external classes (classes that wrap nested classes), and if you want to access an external type, pass the outer class through the constructor to an instance
<3> nested classes can only access static members in external classes, and non-static members of external classes are not directly accessible.
namespaceconsoleapplication11anonymous{classClass1 {Private intx; protected stringstr; Static inty; Public classNested {intxx; stringSS; voidprint () {//int y = x; //error, cannot access external non-static members intz = y;//OK, you can access the external static members } PublicNested (Class1 A) {xx= a.x;//accessing external class private members through an instance of an external classSS = A.str;//to access an external class protection member through an instance of an external class } } } classProgram {Static voidMain (string[] args) {Class1 X=NewClass1 (); class1.nested CN=Newclass1.nested (X); } }}
<4> according to C # scope rules, an external class can access only the public members of the inner class through an instance of the inner class, and cannot access the protected,private.
classClass2 {Private intx; Static Private inty; Public voidfunc () {//x = XX; //The name "XX" does not exist in the current context//x = ZZ; //the name "ZZ" does not exist in the current context//x = AA; //The name "AA" does not exist in the current contextx =Nested.aa; Console.WriteLine (x); } Public voidFuncs () {//This can only access public members of the nested classNested XX =NewNested (); X=Xx.zz; Console.WriteLine (x); //x = XX.AA;//access to static members can only be through the class name and not the instancex =Nested.aa; Console.WriteLine (x); } Private classNested {Private intxx; protected intyy; Public intZZ; Public Static intAA; } }
C # Nested classes