函式覆蓋總結知識點
一個虛擬函式被覆蓋後,任何父類變數都不能訪問該虛擬函式的具體實現。
public virtual void IntroduceMyself(){...}//父類虛擬函式
public new void IntroduceMyself(){...}//子類覆蓋父類虛擬函式
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; ///
/// 父類建構函式 ///
public Person() { this._name = "DefaultName"; this._age = 23; this._gender = Genders.Male; } ///
/// 定義虛擬函式IntroduceMyself() ///
public virtual void IntroduceMyself() { System.Console.WriteLine("Person.IntroduceMyself()"); } ///
/// 定義虛擬函式PrintName() ///
public virtual void PrintName() { System.Console.WriteLine("Person.PrintName()"); } } public class ChinesePerson :Person{ ///
/// 子類建構函式,指明從父類無參建構函式呼叫起 ///
public ChinesePerson() :base(){ this._name = "DefaultChineseName"; } ///
/// 覆蓋父類方法IntroduceMyself,使用new關鍵字修飾虛擬函式 ///
public new void IntroduceMyself() { System.Console.WriteLine("ChinesePerson.IntroduceMyself()"); } ///
/// 過載父類方法PrintName,使用override關鍵字修飾虛擬函式 ///
public override void PrintName(){ System.Console.WriteLine("ChinesePerson.PrintName()"); } } class Program { static void Main(string[] args) { //定義兩個物件,一個父類物件,一個子類物件 Person aPerson = new ChinesePerson(); ChinesePerson cnPerson = new ChinesePerson(); //呼叫覆蓋的方法,父類物件不能呼叫子類覆蓋過的方法,只能呼叫自身的'虛擬函式方法 aPerson.IntroduceMyself(); cnPerson.IntroduceMyself(); //呼叫過載方法,父類物件和子類物件都可以呼叫子類過載過後的方法 aPerson.PrintName(); cnPerson.PrintName(); System.Console.ReadLine(); } }}
結果:
Person.IntroduceMyself()
ChinesePerson.IntroduceMyself()
ChinesePerson.PrintName()
ChinesePerson.PrintName()
以上這篇C# 函式覆蓋總結學習(推薦)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援。