我是OOP的新手,多态性让我很难过:
class Animal { public virtual void eat() { Console.Write("Animal eating"); } } class Dog : Animal { public override void eat() { Console.Write("Dog eating"); } } class Program { public void Main() { Animal dog = new Dog(); Animal generic = new Animal(); dog.eat(); generic.eat(); } }
这样打印
Dog eating Animal eating
但是为什么不使用Dog类型代替动物,比如Dog dog = new Dog()?当你知道这个物体是一种动物,但我不知道它是什么样的动物时,我认为这很方便.请向我解释一下.
谢谢
解决方法
您可以通过其超类引用子类.
Animal dog = new Dog(); Animal cat = new Cat(); Animal frog = new Frog(); List<Animal> animals = new List<Animal>(); animals.add(dog); animals.add(cat); animals.add(frog); foreach(Animal animal in animals) { Console.WriteLine(animal.eat()); }