C#虛方法

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   os   ar   使用   sp   

轉自:http://www.cnblogs.com/ArmyShen/archive/2012/09/02/2667816.html

作用:子類可以對父類中的虛方法進行重寫,虛方法是多態特性的一種體現

C#中的虛方法使用virtual關鍵字定義

public virtual void eat();

override關鍵字作用是對父類的virtual方法進行重寫

public override void eat();

 

代碼舉例:

using System;using System.Collections;public class Animal{    public Animal() { }    public virtual void eat()    {    }}public class dog:Animal{    public override void eat()    {        //如果父類的虛方法中有我們需要的資料,可以在子類的覆蓋方法中調用它:        //base.eat();        Console.WriteLine("狗吃骨頭");    }}public class cat:Animal{    public override void eat()    {        Console.WriteLine("貓吃魚");    }}public class panda:Animal{    public override void eat()    {        Console.WriteLine("熊貓吃竹子");    }}public class MainFun{    static void Main()    {        Animal[] anim = new Animal[3];        anim[0] = new dog();        anim[1] = new cat();        anim[2] = new panda();        anim[0].eat();        anim[1].eat();        anim[2].eat();    }}

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.