【C#】多态
2021-06-30 19:05
标签:div err ring virt 实例化 stat key span ati 直接上代码比较容易记 运行结果。子类重写父类,实例化父类,执行子类方法,若要执行子类new出的方法,则要实例化子类。 【C#】多态 标签:div err ring virt 实例化 stat key span ati 原文地址:https://www.cnblogs.com/xuxml/p/9973862.html public class Animal
{
public virtual void Eat()
{
Console.WriteLine("Animal eat");
Console.ReadKey();
}
}
public class Cat : Animal
{
public override void Eat()
{
Console.WriteLine("Cat eat");
Console.ReadKey();
}
}
public class Dog : Animal
{
public override void Eat()
{
Console.WriteLine("Dog eat");
Console.ReadKey();
}
}
public class Snake : Animal
{
public new void Eat()
{
Console.WriteLine("Snake eat");
Console.ReadKey();
}
}
class Tester
{
static void Main(string[] args)
{
Animal[] animals = new Animal[5];
animals[0] = new Animal();
animals[1] = new Cat();
animals[2] = new Dog();
animals[3] = new Snake();
for (int i = 0; i 4; i++)
{
animals[i].Eat();
}
Snake snake = new Snake();
snake.Eat();
}
}
Animal eat
Cat eat
Dog eat
Animal eat
Snake eat
下一篇:[NGINX]Windows配置