欢迎来到入门教程网!

C#教程

当前位置:主页 > 软件编程 > C#教程 >

C# 函数覆盖总结学习(推荐)

来源:本站原创|时间:2020-01-10|栏目:C#教程|点击:

覆盖类成员:通过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# 函数覆盖总结学习(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

上一篇:分享C#中几个可用的类

栏    目:C#教程

下一篇:浅析C#中StringBuilder类的高效及与String的对比

本文标题:C# 函数覆盖总结学习(推荐)

本文地址:https://www.xiuzhanwang.com/a1/C_jiaocheng/6510.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有