.net父子类与静态和非静态的执行顺序
View Code
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace ConsoleApplication2 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 BaseB b = new BaseB(); 13 b.MyFun(); 14 } 15 } 16 public class MyTest { 17 public MyTest(string info) { 18 Console.WriteLine(info); 19 } 20 } 21 public class BaseA { 22 public static MyTest a1 = new MyTest("a1"); 23 public MyTest a2 = new MyTest("a2"); 24 static BaseA() { 25 MyTest a3 = new MyTest("a3"); 26 } 27 public BaseA() { 28 MyTest a4 = new MyTest("a4"); 29 } 30 public virtual void MyFun() { 31 MyTest a5 = new MyTest("a5"); 32 } 33 } 34 public class BaseB : BaseA { 35 public static MyTest b1 = new MyTest("b1"); 36 public MyTest b2 = new MyTest("b2"); 37 static BaseB() { 38 MyTest b3 = new MyTest("b3"); 39 } 40 public BaseB() { 41 MyTest b4 = new MyTest("b4"); 42 } 43 public new void MyFun() { 44 MyTest b5 = new MyTest("b5"); 45 } 46 } 47 }
答案:
结论:在一个程序中执行顺序:
1.本类静态属性
2.本类静态构造函数
3.本类的属性
4.父类的静态属性
5.父类的静态构造函数
6.父类的属性
7.父类的构造函数
8.本类的构造函数
9.本类的方法