您当前的位置: 首页 >  c#

C#构造函数在继承过程中的执行顺序

发布时间:2010-11-22 15:34:00 ,浏览量:0

using System; class Program     {         static void Main(string[] args)         {             childTest test = new childTest();             childTest test1 = new childTest(2);             childTest test2 = new childTest(2, 3);             Console.Read();         }     }     class baseTest     {        public baseTest()         {             Console.WriteLine("父类构造函数");         }         public baseTest(int i)         {             Console.WriteLine("父类有参数构造函数"+i);         }     }     class childTest:baseTest     {         public childTest()         {             Console.WriteLine("子类无参数构造函数");         }         public childTest(int i)         {             Console.WriteLine("子类有参数构造函数" + i);         }         public childTest(int a, int b):base(a)         {             Console.WriteLine("子类2个参数构造函数");         }     }

以上这段代码的运行结果是:

父类构造函数

子类无参数构造函数

父类构造函数

子类有参数构造函数2

父类有参数构造函数2

子类2个参数构造函数

从运行结果上就可以看到是先执行父类的构造函数,然后再运行子类的构造函数,并且如果不是显示的调用父类的构造函数的话,那就会调用无参数构造函数,反之则不会调用。

关注
打赏
1688896170
查看更多评论

暂无认证

  • 0浏览

    0关注

    104724博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0710s