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个参数构造函数从运行结果可以看出先执行父类的构造函数再执行子类的构造函数。如果没有显式调用父类的构造函数则会默认调用父类的无参数构造函数反之如果显式调用了父类的有参数构造函数则不会调用无参数构造函数。
阅读完成 · 觉得有帮助?