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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值