C#語言基礎知識(2):C#中多態

來源:互聯網
上載者:User

標籤:style   blog   color   for   line   div   

我的理解是:通過繼承實現的不同對象調用相同的方法,表現出不同的行為,稱之為多態.
1: OverRide 實現多態

 1 public class Animal 2     { 3         public virtual void Eat() 4         { 5             Console.WriteLine("Animal eat"); 6         } 7     } 8     public class Dog : Animal 9     {10         public override void Eat()11         {12             Console.WriteLine("Dog eat");13         }14     }15     public class WolfDog : Dog16     {17         public override void Eat()18         {19             Console.WriteLine("WolfDog eat");20         }21     }22     class Tester23     {24         static void Main(string[] args)25         {26             Animal[] animals = new Animal[3];27             animals[0] = new Animal();28             animals[1] = new Dog();29             animals[2] = new WolfDog();30             for (int i = 0; i < 3; i++)31             {32                 animals[i].Eat();33             }34         }35 }

運行結果為:
Animal eat...
Dog eat...
WolfDog eat...
2:New虛方法實現多態

 1 public class Animal 2     { 3         public virtual void Eat() 4         { 5             Console.WriteLine("Animal eat"); 6         } 7     } 8     public class Cat : Animal 9     {10         public new void Eat()11         {12             Console.WriteLine("Cat eat");13         }14     }15     class Tester16     {17         static void Main(string[] args)18 19         {20             Animal a = new Animal();21             a.Eat();22             Animal ac = new Cat();23             ac.Eat();24             Cat c = new Cat();25             c.Eat();26         }27     }

輸出結果如下
Animal eat...
Animal eat...
Cat eat...

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.