类的实例化过程(C#为例)

来源:互联网 发布:加拿大预测软件 编辑:程序博客网 时间:2024/05/17 21:30
1.属性、方法不需要初始化,因为这些全部是指针。 
2.初始化派生类的静态字段。 
3.初始化派生类的非静态字段。 
4.初始化基类的静态字段。 
5.初始化基类的非静态字段。 
6.调用基类的构造函数。 

7.调用派生类的构造函数。 

其实就是实例化的顺序,用语言本身或者调试都是不错的验证方法.估计其他oop也差不多这个顺序吧


外加注释: 
静态字段和静态构造函数,是初次使用该类的时候初始化和运行的 
所以,如果以前已经使用过某类,就不会再初始化该类的静态字段 

一个更突显过程的例子: 

        class   Program 
        { 
                static   void   Main(string[]   args) 
                { 
                        C   c   =   new   C(); 
                        Console.ReadLine(); 
                } 
        } 

        class   Tester   //   该Tester可帮我们跟踪实例化的过程 
        { 
                public   Tester(string   msg)   {   Console.WriteLine(msg);   } 
        } 

        class   A 
        { 
                static   Tester   AStatic   =   new   Tester( "A   static "); 
                Tester   AInstance   =   new   Tester( "A   instance "); 
                public   A()   {   AInstance   =   new   Tester( "A   constructor ");   } 
        } 

        class   B   :   A 
        { 
                static   Tester   BStatic   =   new   Tester( "B   static "); 
                Tester   BInstance   =   new   Tester( "B   instance "); 
                public   B()   {   BInstance   =   new   Tester( "B   constructor ");   } 
        } 

        class   C   :   B 
        { 
                static   Tester   CStatic   =   new   Tester( "C   static "); 
                Tester   CInstance   =   new   Tester( "C   instance "); 
                public   C()   {   CInstance   =   new   Tester( "C   constructor ");   } 
        } 

结果: 

C   static 
C   instance 
B   static 
B   instance 
A   static 
A   instance 
A   constructor 
B   constructor 
C   constructor