深入剖析C#继承机制
通過base 關(guān)鍵字訪問基類的成員:
調(diào)用基類上已被其他方法重寫的方法。
指定創(chuàng)建派生類實(shí)例時(shí)應(yīng)調(diào)用的基類構(gòu)造函數(shù)。
基類訪問只能在構(gòu)造函數(shù)、實(shí)例方法或?qū)嵗龑傩栽L問器中進(jìn)行。
從靜態(tài)方法中使用 base 關(guān)鍵字是錯(cuò)誤的。
示例:下面程序中基類 Person 和派生類 Employee 都有一個(gè)名為 Getinfo 的方法。通過使用 base 關(guān)鍵字,可以從派生類中調(diào)用基類上的 Getinfo 方法。
?
| using System ; public class Person { protected string ssn = "111-222-333-444" ; protected string name = "張三" ; public virtual void GetInfo() { Console.WriteLine("姓名: {0}", name) ; Console.WriteLine("編號(hào): {0}", ssn) ; } } class Employee: Person { public string id = "ABC567EFG23267" ; public override void GetInfo() { // 調(diào)用基類的GetInfo方法: base.GetInfo(); Console.WriteLine("成員ID: {0}", id) ; } } class TestClass { public static void Main() { Employee E = new Employee() ; E.GetInfo() ; } } |
程序運(yùn)行輸出:
姓名: 張三
編號(hào): 111-222-333-444
成員ID: ABC567EFG23267
示例:派生類同基類進(jìn)行通信。
| using System ; public class Parent { string parentString; public Parent( ) { Console.WriteLine("Parent Constructor.") ; } public Parent(string myString) { parentString = myString; Console.WriteLine(parentString) ; } public void print( ) { Console.WriteLine("I'm a Parent Class.") ; } } public class Child : Parent { public Child( ) : base("From Derived") { Console.WriteLine("Child Constructor.") ; } public void print( ) { base.print( ) ; Console.WriteLine("I'm a Child Class.") ; } public static void Main( ) { Child child = new Child( ) ; child.print( ) ; ((Parent)child).print( ) ; } } |
程序運(yùn)行輸出:
From Derived
Child Constructor.
I'm a Parent Class.
I'm a Child Class.
I'm a Parent Class.
說明:
1.派生類在初始化的過程中可以同基類進(jìn)行通信。
上面代碼演示了在子類的構(gòu)造函數(shù)定義中是如何實(shí)現(xiàn)同基類通信的。分號(hào)":"和關(guān)鍵字base用來調(diào)用帶有相應(yīng)參數(shù)的基類的構(gòu)造函數(shù)。輸出結(jié)果中,第一行表明:基類的構(gòu)造函數(shù)最先被調(diào)用,其實(shí)在參數(shù)是字符串"From Derived"。
2.有時(shí),對(duì)于基類已有定義的方法,打算重新定義自己的實(shí)現(xiàn)。
Child類可以自己重新定義print( )方法的實(shí)現(xiàn)。Child的print( )方法覆蓋了Parent中的 print 方法。結(jié)果是:除非經(jīng)過特別指明,Parent類中的print方法不會(huì)被調(diào)用。
3.在Child類的 print( ) 方法中,我們特別指明:調(diào)用的是Parent類中的 print( ) 方法。
方法名前面為"base",一旦使用"base"關(guān)鍵字之后,你就可以訪問基類的具有公有或者保護(hù)權(quán)限的成員。 Child類中的print( )方法的執(zhí)行結(jié)果出現(xiàn)上面的第三行和第四行。
4.訪問基類成員的另外一種方法是:通過顯式類型轉(zhuǎn)換。
在Child類的Main( )方法中的最后一條語(yǔ)句就是這么做的。記住:派生類是其基類的特例。這個(gè)事實(shí)告訴我們:可以在派生類中進(jìn)行數(shù)據(jù)類型的轉(zhuǎn)換,使其成為基類的一個(gè)實(shí)例。上面代碼的最后一行實(shí)際上執(zhí)行了Parent類中的 print( )方法。
摘自天極網(wǎng) 天雨
轉(zhuǎn)載于:https://www.cnblogs.com/Lee_Allen/archive/2008/10/22/1316561.html
總結(jié)
以上是生活随笔為你收集整理的深入剖析C#继承机制的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TRIE - Data Structur
- 下一篇: SAP的程序用客户端连接正常,用C#连接