为什么以及何时使用多态? [英] Why and when use polymorphism?
本文介绍了为什么以及何时使用多态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 OOP 的新手,多态让我很难过:
I'm new to OOP and polymorphism has given me a hard time:
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()?我认为当您知道对象是动物但不知道它是哪种动物时,这会很方便.请给我解释一下.
But why not to just use the Dog type instead of animal, like Dog dog = new Dog()? I assume this comes handy when you know the object is a animal, but don't know what kind of animal it is. Please explain this to me.
谢谢
推荐答案
您可以通过子类的超类来引用子类.
You can refer to a subclass by its super class.
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());
}
这篇关于为什么以及何时使用多态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文