C# 函數(shù)覆蓋總結(jié)學(xué)習(xí)(推薦)
覆蓋類成員:通過(guò)new關(guān)鍵字修飾虛函數(shù)表示覆蓋該虛函數(shù)。
一個(gè)虛函數(shù)被覆蓋后,任何父類變量都不能訪問該虛函數(shù)的具體實(shí)現(xiàn)。
public virtual void IntroduceMyself(){...}//父類虛函數(shù)
public new void IntroduceMyself(){...}//子類覆蓋父類虛函數(shù)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MethodOverrideByNew { public enum Genders { Female=0, Male=1 } public class Person { protected string _name; protected int _age; protected Genders _gender; /// <summary> /// 父類構(gòu)造函數(shù) /// </summary> public Person() { this._name = "DefaultName"; this._age = 23; this._gender = Genders.Male; } /// <summary> /// 定義虛函數(shù)IntroduceMyself() /// </summary> public virtual void IntroduceMyself() { System.Console.WriteLine("Person.IntroduceMyself()"); } /// <summary> /// 定義虛函數(shù)PrintName() /// </summary> public virtual void PrintName() { System.Console.WriteLine("Person.PrintName()"); } } public class ChinesePerson :Person{ /// <summary> /// 子類構(gòu)造函數(shù),指明從父類無(wú)參構(gòu)造函數(shù)調(diào)用起 /// </summary> public ChinesePerson() :base(){ this._name = "DefaultChineseName"; } /// <summary> /// 覆蓋父類方法IntroduceMyself,使用new關(guān)鍵字修飾虛函數(shù) /// </summary> public new void IntroduceMyself() { System.Console.WriteLine("ChinesePerson.IntroduceMyself()"); } /// <summary> /// 重載父類方法PrintName,使用override關(guān)鍵字修飾虛函數(shù) /// </summary> public override void PrintName(){ System.Console.WriteLine("ChinesePerson.PrintName()"); } } class Program { static void Main(string[] args) { //定義兩個(gè)對(duì)象,一個(gè)父類對(duì)象,一個(gè)子類對(duì)象 Person aPerson = new ChinesePerson(); ChinesePerson cnPerson = new ChinesePerson(); //調(diào)用覆蓋的方法,父類對(duì)象不能調(diào)用子類覆蓋過(guò)的方法,只能調(diào)用自身的虛函數(shù)方法 aPerson.IntroduceMyself(); cnPerson.IntroduceMyself(); //調(diào)用重載方法,父類對(duì)象和子類對(duì)象都可以調(diào)用子類重載過(guò)后的方法 aPerson.PrintName(); cnPerson.PrintName(); System.Console.ReadLine(); } } }
結(jié)果:
Person.IntroduceMyself()
ChinesePerson.IntroduceMyself()
ChinesePerson.PrintName()
ChinesePerson.PrintName()
以上這篇C# 函數(shù)覆蓋總結(jié)學(xué)習(xí)(推薦)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#將Word或Excel文檔轉(zhuǎn)換為Html文件
這篇文章介紹了C#將Word或Excel文檔轉(zhuǎn)換為Html文件的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06C#?Winform實(shí)現(xiàn)復(fù)制文件顯示進(jìn)度
這篇文章主要介紹了C#?Winform實(shí)現(xiàn)復(fù)制文件顯示進(jìn)度,用進(jìn)度條來(lái)顯示復(fù)制情況,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-07-07直接在線預(yù)覽Word、Excel、TXT文件之ASP.NET
這篇文章主要用asp.net技術(shù)實(shí)現(xiàn)直接在線預(yù)覽word、excel、txt文件,有需要的朋友可以參考下2015-08-08基于WPF實(shí)現(xiàn)跳動(dòng)的字符效果
這篇文章主要和大家介紹一個(gè)好玩但實(shí)際作用可能不太大的動(dòng)畫效果:跳動(dòng)的字符,本文將利用WPF實(shí)現(xiàn)這一效果,感興趣的小伙伴可以學(xué)習(xí)一下2023-08-08