當前位置:學問谷 >

行政範例 >總結 >

函式覆蓋總結知識點

函式覆蓋總結知識點

一個虛擬函式被覆蓋後,任何父類變數都不能訪問該虛擬函式的具體實現。

函式覆蓋總結知識點

public virtual void IntroduceMyself(){...}//父類虛擬函式

public new void IntroduceMyself(){...}//子類覆蓋父類虛擬函式

using System;using ric;using ;using ;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 = ; } ///

/// 定義虛擬函式IntroduceMyself() ///

public virtual void IntroduceMyself() { eLine("oduceMyself()"); } ///

/// 定義虛擬函式PrintName() ///

public virtual void PrintName() { eLine("tName()"); } } public class ChinesePerson :Person{ ///

/// 子類建構函式,指明從父類無參建構函式呼叫起 ///

public ChinesePerson() :base(){ this._name = "DefaultChineseName"; } ///

/// 覆蓋父類方法IntroduceMyself,使用new關鍵字修飾虛擬函式 ///

public new void IntroduceMyself() { eLine("oduceMyself()"); } ///

/// 過載父類方法PrintName,使用override關鍵字修飾虛擬函式 ///

public override void PrintName(){ eLine("tName()"); } } class Program { static void Main(string[] args) { //定義兩個物件,一個父類物件,一個子類物件 Person aPerson = new ChinesePerson(); ChinesePerson cnPerson = new ChinesePerson(); //呼叫覆蓋的方法,父類物件不能呼叫子類覆蓋過的.方法,只能呼叫自身的虛擬函式方法 oduceMyself(); oduceMyself(); //呼叫過載方法,父類物件和子類物件都可以呼叫子類過載過後的方法 tName(); tName(); Line(); } }}

結果:

oduceMyself()

oduceMyself()

tName()

tName()

以上這篇C# 函式覆蓋總結學習(推薦)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援。

標籤: 知識點 函式 覆蓋
  • 文章版權屬於文章作者所有,轉載請註明 https://xuewengu.com/zh-tw/flxz/zongjie/6vydqr.html