一个虚函数被覆盖后,任何父类变量都不能访问该虚函数的具体实现。
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# 函数覆盖总结学习(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。