virtual與abstract方法使用上的區別

     virtual 與abstract在修飾方法上都是表示虛擬方法,但是在使用上存在區別 。  


       

     virtual:如果派生類中沒有重寫方法,那麼在實例化派生類之後,按基類方法執行,如果基類已經重寫了方法,則用派生類方法執行 。

      abstract :基類必須爲abstract類,方法並沒有具體內容,只是在派生類中會對應方法內容。

 
舉個例子,老師叫小明和小紅去讀課文,小紅是個乖寶寶,就直接按老師的建議去做,但是小明想玩王者榮耀,所以就用override屏蔽了老師的話,具體程式如下,就可以用virtual了。


   class Program
    {
        static void Main(string[] args)
        {
            xiaoming ccxiaoming = new xiaoming();
            ccxiaoming.suggestion();
            xiaohong ccxiaohong = new xiaohong();
            ccxiaohong.suggestion();
            Console.ReadLine();
        }
    }

    class xiaoming : teacherCommand
    {
        public xiaoming():base()
        {
           
        }
        public override void suggestion()
        {
            Console.WriteLine("play game");
        }
    }

    class xiaohong : teacherCommand
    {
        public xiaohong()
            : base()
        {
           
        }
    }

    class teacherCommand {
    public  virtual void  suggestion() {
            Console.WriteLine("read this article");
        }
    }

結果是:

play game

read this article


再舉個例子,老師給小紅和小明留了家庭作業要幫助家人做家務,但是並沒有說要做什麼,小明就幫媽媽打掃房間,而小紅則是幫爺爺讀報紙。

class Program
    {
        static void Main(string[] args)
        {
            xiaoming ccxiaoming = new xiaoming();
            ccxiaoming.housework();
            xiaohong ccxiaohong = new xiaohong();
            ccxiaohong.housework();
            Console.ReadLine();
        }
    }


    class xiaoming : homework
    {
        public override void housework()
        {
            Console.WriteLine("help mother clean the room");
        }
    }

    class xiaohong : homework
    {
        public override void housework()
        {
            Console.WriteLine("help grandpa read the newspaper ");
        }
    }
      
    abstract class homework {
         abstract void housework();
    }

結果是:

help mother clean the room


help grandpa read the newspaper




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章