C# 函数覆盖总结学习(推荐)
覆盖类成员:通过new关键字修饰虚函数表示覆盖该虚函数。
一个虚函数被覆盖后,任何父类变量都不能访问该虚函数的具体实现。
publicvirtualvoidIntroduceMyself(){...}//父类虚函数
publicnewvoidIntroduceMyself(){...}//子类覆盖父类虚函数
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespaceMethodOverrideByNew
{
publicenumGenders{
Female=0,
Male=1
}
publicclassPerson{
protectedstring_name;
protectedint_age;
protectedGenders_gender;
///<summary>
///父类构造函数
///</summary>
publicPerson(){
this._name="DefaultName";
this._age=23;
this._gender=Genders.Male;
}
///<summary>
///定义虚函数IntroduceMyself()
///</summary>
publicvirtualvoidIntroduceMyself(){
System.Console.WriteLine("Person.IntroduceMyself()");
}
///<summary>
///定义虚函数PrintName()
///</summary>
publicvirtualvoidPrintName(){
System.Console.WriteLine("Person.PrintName()");
}
}
publicclassChinesePerson:Person{
///<summary>
///子类构造函数,指明从父类无参构造函数调用起
///</summary>
publicChinesePerson():base(){
this._name="DefaultChineseName";
}
///<summary>
///覆盖父类方法IntroduceMyself,使用new关键字修饰虚函数
///</summary>
publicnewvoidIntroduceMyself(){
System.Console.WriteLine("ChinesePerson.IntroduceMyself()");
}
///<summary>
///重载父类方法PrintName,使用override关键字修饰虚函数
///</summary>
publicoverridevoidPrintName(){
System.Console.WriteLine("ChinesePerson.PrintName()");
}
}
classProgram
{
staticvoidMain(string[]args)
{
//定义两个对象,一个父类对象,一个子类对象
PersonaPerson=newChinesePerson();
ChinesePersoncnPerson=newChinesePerson();
//调用覆盖的方法,父类对象不能调用子类覆盖过的方法,只能调用自身的虚函数方法
aPerson.IntroduceMyself();
cnPerson.IntroduceMyself();
//调用重载方法,父类对象和子类对象都可以调用子类重载过后的方法
aPerson.PrintName();
cnPerson.PrintName();
System.Console.ReadLine();
}
}
}
结果:
Person.IntroduceMyself()
ChinesePerson.IntroduceMyself()
ChinesePerson.PrintName()
ChinesePerson.PrintName()
以上这篇C#函数覆盖总结学习(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语