你在基类中不是写了一个虚方法吗?当在程序中调用这个虚方法时,运行时可以判定应该具体调用哪个方法.其实这个时候系统调用的是最底层的派生方法,如果原始虚方法没有被重载,那么最底层的派生方法就是原始虚方法,否则最底层的派生方法就是相应对象(派生类的实例)中的重载方法.
这里有一个例子
using System;
namespace LearningCSharp
{
public class Animal //基类
{
public Animal() {}
public void Sleep() {}
public bool ISHungry=true;
public virtual void Eat()
{
Consloe.WriteLine("Eat Something");
}
}
public class Elephant : Animal
{
public override void Eat()
{
Console.WriteLine("Eat grass");
}
}
public class Mouse : Animal
{
public override void Eat()
{
Console.WriteLine("Eat cheese");
}
}
public class Cat : Animal
{
public override void Eat()
{
Console.WriteLine("Eat mouse");
}
}
public class WildLife
{
public WildLife()
{
Elephant myElephant=new Elephant();
Mouse myMouse=new Mouse();
Cat myCat=new Cat();
FeedingTime(myElephant);
FeedingTime(myMouse);
FeedingTime(myCat);
}
public void FeedTime(Animal someCreature)
{
if(someCreature.ISHungry)
{
someCreature.Eat();
}
}
static void Main(string[] args)
{
WildLife w=new WildLife();
}
}
}
运行结果如下:
Eat grass
Eat cheese
Eat mouse