標籤:
多態的概念:通過繼承實現的不同對象調用相同的方法,表現出不同的行為,稱之為多態
override實現多態
public class Animal { public virtual void Eat() { Console.WriteLine("Animal eat"); } } public class Dog : Animal { public override void Eat() { Console.WriteLine("Dog eat"); } } public class WolfDog : Dog { public override void Eat() { Console.WriteLine("WolfDog eat"); } } class Tester { static void Main(string[] args) { Animal[] animals = new Animal[3]; animals[0] = new Animal(); animals[1] = new Dog(); animals[2] = new WolfDog(); for (int i = 0; i < 3; i++) { animals[i].Eat(); } }}
abstract-override實現多態
public abstract class Animal { public abstract void Eat(); } public class Cat : Animal { public override void Eat() { Console.WriteLine("Cat eat"); } } public class Dog : Animal { public override void Eat() { Console.WriteLine("Dog eat"); } } public class WolfDog : Dog { public override void Eat() { Console.WriteLine("Wolfdog eat"); } } class Tester { static void Main(string[] args) { Animal[] animals = new Animal[3]; animals[0] = new Cat(); animals[1] = new Dog(); animals[2] = new WolfDog(); for (int i = 0; i < animals.Length; i++) { animals[i].Eat(); } } }
C#-----多態