三个类:父类,子类,测试类
父类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System;
2
3 namespace TestInherit
4 {
5 public class Father
6 {
7 public int father_a=111;
8 public int father_aa=1111;
9 public readonly int father_c=7777;
10 public static int father_e=222;
11 public static int father_ee;
12 static Father()
13 {
14 father_e=5555;
15 father_ee=3333;
16 }
17
18 public Father()
19 {
20 father_ee=4444;
21 }
22 public Father(int a)
23 {
24 father_a=a;
25 }
26 }
27 }
2
3 namespace TestInherit
4 {
5 public class Father
6 {
7 public int father_a=111;
8 public int father_aa=1111;
9 public readonly int father_c=7777;
10 public static int father_e=222;
11 public static int father_ee;
12 static Father()
13 {
14 father_e=5555;
15 father_ee=3333;
16 }
17
18 public Father()
19 {
20 father_ee=4444;
21 }
22 public Father(int a)
23 {
24 father_a=a;
25 }
26 }
27 }
子类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System;
2
3 namespace TestInherit
4 {
5 public class Son:Father
6 {
7 public int son_int=9999;
8 public static int son_b=111;
9 public static int son_c;
10 public Son()
11 {
12 son_c=222;
13 }
14 static Son()
15 {
16 son_c=333;
17 }
18 public Son(int a)
19 {
20 son_int=a;
21 }
22 }
23 }
2
3 namespace TestInherit
4 {
5 public class Son:Father
6 {
7 public int son_int=9999;
8 public static int son_b=111;
9 public static int son_c;
10 public Son()
11 {
12 son_c=222;
13 }
14 static Son()
15 {
16 son_c=333;
17 }
18 public Son(int a)
19 {
20 son_int=a;
21 }
22 }
23 }
测试类:
1 using System;
2
3 namespace TestInherit
4 {
5 class Class1
6 {
7 [STAThread]
8 static void Main(string[] args)
9 {
10 Son son1=new Son ();
11 }
12 }
13 }
2
3 namespace TestInherit
4 {
5 class Class1
6 {
7 [STAThread]
8 static void Main(string[] args)
9 {
10 Son son1=new Son ();
11 }
12 }
13 }
然后一路F11,进行跟踪,可以得到完整的执行顺序如下所示:
1.子类静态变量;
2.子类静态构造函数;
3.子类非静态变量;
4.父类静态变量;
5.父类静态构造函数;
6.父类非静态变量;
7.父类无参构造函数;
8.子类无参构造函数;
如果Main()方法中改为Son son1=new Son (111),顺序为;
1.子类静态变量;
2.子类静态构造函数;
3.子类非静态变量;
4.父类静态变量;
5.父类静态构造函数;
6.父类非静态变量;
7.父类无参构造函数;
8.子类有参构造函数;
如果子类的有参构造函数改为:
public Son(int a):base(a)
{
son_int=a;
}
则顺序又有所改变:
1.子类静态变量;
2.子类静态构造函数;
3.子类非静态变量;
4.父类静态变量;
5.父类静态构造函数;
6.父类非静态变量;
7.父类有参构造函数;
8.子类有参构造函数;
以上测试改为父类声明,子类实现,结果也是一样,即mian()方法中改为Father son1=new Son ();
最后作一个总结:
1.一般原理是被依赖的先构造,依赖于人的后构造,c#中是同层依赖(成员变量,其他的类变量等)优先于跨层依赖(父子关系)构造(注意java中正好相反);(子类的变量是不是可以理解为同层的依赖呢??)
2.静态构造函数,静态参数都是优先于非静态构造函数,非静态参数构造或初始化;