C# 嵌套类

from:https://blog.csdn.net/ddupd/article/details/21905573

嵌套类顾名思义就是类或者结构中定义的类

[csharp]  view plain  copy
 
  1. class Container  
  2. {  
  3.     class Nested  
  4.     {  
  5.         Nested() { }  
  6.     }  
  7. }  



<1>嵌套类的默认访问权限是private ,可以指定为public,protected,private,internal,protected internal。
<2>嵌套类型可以访问外部类(包裹嵌套类的类),如果要访问外部类型,要把外部类通过构造函数传进一个实例
<3>嵌套类中只能访问外部类中的静态成员,不能直接访问外部类的非静态成员。

[csharp]  view plain  copy
 
  1. namespace ConsoleApplication11Anonymous  
  2. {  
  3.     class Class1  
  4.     {  
  5.         private int x;  
  6.         protected string str;  
  7.         static int y;  
  8.   
  9.   
  10.         public class Nested  
  11.         {  
  12.             int xx;  
  13.             string ss;  
  14.             void print()  
  15.             {  
  16.                 //int y = x;  //error,不能访问外部的非静态成员  
  17.                 int z = y;    //OK ,可以访问外部的静态成员  
  18.             }  
  19.   
  20.   
  21.             public Nested(Class1 A)  
  22.             {  
  23.                 xx = A.x;   //通过外部类的实例来访问外部类私有成员  
  24.                 ss = A.str; //通过外部类的实例来访问外部类保护成员  
  25.             }  
  26.         }  
  27.     }  
  28.   
  29.   
  30.     class Program  
  31.     {  
  32.         static void Main(string[] args)  
  33.         {  
  34.              
  35.             Class1 X = new Class1();  
  36.             Class1.Nested CN = new Class1.Nested( X );  
  37.               
  38.   
  39.   
  40.         }  
  41.   
  42.   
  43.     }  
  44. }  

<4>根据C#作用域的规则,外部类只能通过内部类的实例来访问内部类的public成员,不能访问protected,private。

[csharp]  view plain  copy
 
    1. class Class2  
    2.     {  
    3.         private int x;  
    4.         static private int y;  
    5.   
    6.         public void func()  
    7.         {  
    8.             //x = xx;   //当前上下文中不存在名称“xx”  
    9.             //x = zz;   //当前上下文中不存在名称“zz”  
    10.             //x = aa;   //当前上下文中不存在名称“aa”  
    11.             x = Nested.aa;  
    12.             Console.WriteLine(x);  
    13.         }  
    14.   
    15.         public void funcs()  
    16.         {  
    17.             //这个只能访问Nested类的public成员  
    18.             Nested XX = new Nested();  
    19.             x = XX.zz;  
    20.             Console.WriteLine(x);  
    21.             //x = XX.aa;//访问静态成员只能通过类名而不是实例  
    22.             x = Nested.aa;  
    23.             Console.WriteLine(x);  
    24.         }  
    25.   
    26.         private class Nested  
    27.         {  
    28.             private int xx;  
    29.             protected int yy;  
    30.             public int zz;  
    31.             public static int aa;  
    32.               
    33.         }  
    34.     }  

猜你喜欢

转载自www.cnblogs.com/liuqiyun/p/9110356.html