C#繼承構(gòu)造函數(shù)實(shí)現(xiàn)及調(diào)用淺析
C#類的繼承,構(gòu)造函數(shù)實(shí)現(xiàn)及其調(diào)用順序
類層層派生,在實(shí)例化的時(shí)候構(gòu)造函數(shù)的調(diào)用順序是怎樣的? --從頂層基類開(kāi)始向子類方向順序調(diào)用無(wú)參構(gòu)造.
默認(rèn)構(gòu)造(無(wú)參構(gòu)造)和帶參構(gòu)造什么時(shí)候調(diào)用?--默認(rèn)將從頂層父類的默認(rèn)構(gòu)造一直調(diào)用到當(dāng)前類的默認(rèn)構(gòu)造.
下面是C#繼承構(gòu)造函數(shù)實(shí)現(xiàn)及調(diào)用示例:
- /**//*--===------------------------------------------===---
- 作者:許明會(huì)
- 日期:類的派生和構(gòu)造函數(shù)間的關(guān)系,調(diào)用層次及實(shí)現(xiàn)
- 日期:2009年7月18日 17:30:43
- 若希望類能夠有派生類,必須為其實(shí)現(xiàn)默認(rèn)構(gòu)造函數(shù).
- 若類沒(méi)有實(shí)現(xiàn)帶參構(gòu)造,編譯器將自動(dòng)創(chuàng)建默認(rèn)構(gòu)造函數(shù).
- 若類實(shí)現(xiàn)了帶參構(gòu)造,則編譯器不會(huì)自動(dòng)生成默認(rèn)構(gòu)造.
- --===------------------------------------------===---*/
- using System; //C#繼承構(gòu)造函數(shù)實(shí)現(xiàn)及調(diào)用
- namespace xumh
- {
- public class MyClass
- {
- public MyClass()
- {
- Console.WriteLine("MyClass:默認(rèn)構(gòu)造函數(shù)");
- }
- public MyClass(int a, int b)
- {
- Console.WriteLine("MyClass帶參構(gòu)造:a={0}, b={1}.", a, b);
- }
- }
- public class MyClass2 : MyClass
- {
- public MyClass2()
- {
- Console.WriteLine("MyClass2:默認(rèn)構(gòu)造函數(shù)");
- }
- public MyClass2(int a, int b)
- {
- Console.WriteLine("MyClass2帶參構(gòu)造:a={0}, b={1}.", a, b);
- }
- }
- //C#繼承構(gòu)造函數(shù)實(shí)現(xiàn)及調(diào)用
- public class MyClass3 : MyClass2
- {
- public MyClass3()
- {
- Console.WriteLine("MyClass3:默認(rèn)構(gòu)造函數(shù)");
- }
- public MyClass3(int a, int b)
- {
- Console.WriteLine("MyClass3帶參構(gòu)造:a={0}, b={1}.", a, b);
- }
- }
- public class runMyApp
- {
- static void Main()
- {
- MyClass3 my = new MyClass3(3,4);
- }
- }
- } //C#繼承構(gòu)造函數(shù)實(shí)現(xiàn)及調(diào)用
- /**//*--===------------------------------------------===---
- 輸出如下:
- MyClass:默認(rèn)構(gòu)造函數(shù)
- MyClass2:默認(rèn)構(gòu)造函數(shù)
- MyClass3帶參構(gòu)造:a=3, b=4.
- --===------------------------------------------===---*/
C#繼承構(gòu)造函數(shù)實(shí)現(xiàn)及調(diào)用的基本情況就向你介紹到這里,希望對(duì)你學(xué)習(xí)了解C#繼承構(gòu)造函數(shù)實(shí)現(xiàn)及調(diào)用有所幫助。
【編輯推薦】