C#繼承與構(gòu)造函數(shù)的調(diào)用實(shí)例演示
作者:佚名
C#繼承構(gòu)造函數(shù)的調(diào)用實(shí)例演示向你介紹了在實(shí)際操作過程中C#繼承構(gòu)造函數(shù)的調(diào)用順序以及步驟。
C#繼承構(gòu)造函數(shù)的調(diào)用實(shí)例演示
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace test
- {
- class Program
- {
- static void Main(string[] args)
- {
- //***種情況 --C#繼承構(gòu)造函數(shù)的調(diào)用
- A a = new B();//x=1,y=0
- a.PrintFields();//x=1,y=-1
- //因?yàn)闃?gòu)造B之前,先執(zhí)行變量,y沒有明確賦值,默認(rèn)為0。
- //A構(gòu)造函數(shù)調(diào)用的PrintFields方法在A類里是虛函數(shù),它的實(shí)現(xiàn)是在B類,
- //所以執(zhí)行B類的PrintFields方法,結(jié)果輸出。
- //雖然繼續(xù)執(zhí)行完B的構(gòu)造函數(shù),使y的值是-1.但結(jié)果之前已經(jīng)輸出
- //第二種情況 --C#繼承構(gòu)造函數(shù)的調(diào)用
- B b = new B();//x=1,y=0
- b.PrintFields();//x=1,y=-1
- //因?yàn)闃?gòu)造B之前,先執(zhí)行變量,y沒有明確賦值,默認(rèn)為0。
- //執(zhí)行B的構(gòu)造函數(shù),因?yàn)锽繼承A,所以先執(zhí)行A的構(gòu)造函數(shù)。//
- A構(gòu)造函數(shù)調(diào)用的PrintFields方法在A類里是虛函數(shù),它的實(shí)現(xiàn)是在B類,
- //所以執(zhí)行B類的PrintFields方法,結(jié)果輸出。
- //雖然繼續(xù)執(zhí)行完B的構(gòu)造函數(shù),使y的值是-1.但結(jié)果之前已經(jīng)輸出 //第三種情況
- A c = new A();
- c.PrintFields();//什么都不輸出
- Console.ReadKey();
- }
- }
- class A //C#繼承構(gòu)造函數(shù)的調(diào)用
- {
- public A()
- {
- PrintFields();
- }
- public virtual void PrintFields()
- { }
- }
- class B : A
- {
- int x = 1;
- int y;
- public B()
- {
- y = -1;
- }
- public override void PrintFields()
- {
- Console.WriteLine("x={0},y={1}", x, y);
- }
- }
- }
C#繼承構(gòu)造函數(shù)的調(diào)用的基本情況就向你介紹到這里,希望對(duì)你學(xué)習(xí)和掌握C#繼承構(gòu)造函數(shù)的調(diào)用有所幫助。
【編輯推薦】
責(zé)任編輯:仲衡
來源:
中國自學(xué)編程網(wǎng)