白羽
2018-07-05
来源 :网络
阅读 1713
评论 0
摘要:本文将带你了解C#编程函数覆盖总结学习,希望本文对大家学C#/.Net有所帮助。
覆盖类成员:通过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()
以上就介绍了C#.NET的相关知识,希望对C#.NET有兴趣的朋友有所帮助。了解更多内容,请关注职坐标编程语言C#.NET频道!
喜欢 | 0
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号