C# 函数覆盖

覆盖类成员:通过new关键字修饰虚函数表示覆盖该虚函数。
一个虚函数被覆盖后,任何父类变量都不能访问该虚函数的具体实现。
public virtual void IntroduceMyself(){...}//父类虚函数
public new void IntroduceMyself(){...}//子类覆盖父类虚函数

<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->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()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值