C# 函數覆蓋總結學習(推薦)_C#教程

來源:互聯網
上載者:User

覆蓋類成員:通過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# 函數覆蓋總結學習(推薦)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.