覆蓋類成員:通過new關鍵字修飾虛函數表示覆蓋該虛函數。
一個虛函數被覆蓋後,任何父類變量都不能訪問該虛函數的具體實現。
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;
/// <summary>
/// 父類構造函數
/// </summary>
public Person() {
this._name = "DefaultName";
this._age = 23;
this._gender = Genders.Male;
}
/// <summary>
/// 定義虛函數IntroduceMyself()
/// </summary>
public virtual void IntroduceMyself() {
System.Console.WriteLine("Person.IntroduceMyself()");
}
/// <summary>
/// 定義虛函數PrintName()
/// </summary>
public virtual void PrintName() {
System.Console.WriteLine("Person.PrintName()");
}
}
public class ChinesePerson :Person{
/// <summary>
/// 子類構造函數,指明從父類無參構造函數調用起
/// </summary>
public ChinesePerson() :base(){
this._name = "DefaultChineseName";
}
/// <summary>
/// 覆蓋父類方法IntroduceMyself,使用new關鍵字修飾虛函數
/// </summary>
public new void IntroduceMyself() {
System.Console.WriteLine("ChinesePerson.IntroduceMyself()");
}
/// <summary>
/// 重載父類方法PrintName,使用override關鍵字修飾虛函數
/// </summary>
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()