转自:http://www.cnblogs.com/ArmyShen/archive/2012/09/02/2667816.html
作用:子类可以对父类中的虚方法进行重写,虚方法是多态特性的一种体现
C#中的虚方法使用virtual关键字定义
public virtual void eat();
override关键字作用是对父类的virtual方法进行重写
public override void eat();
代码举例:
using System;
using System.Collections;
public class Animal
{
public Animal() { }
public virtual void eat()
{
}
}
public class dog:Animal
{
public override void eat()
{
//如果父类的虚方法中有我们需要的数据,可以在子类的覆盖方法中调用它:
//base.eat();
Console.WriteLine("狗吃骨头");
}
}
public class cat:Animal
{
public override void eat()
{
Console.WriteLine("猫吃鱼");
}
}
public class panda:Animal
{
public override void eat()
{
Console.WriteLine("熊猫吃竹子");
}
}
public class MainFun
{
static void Main()
{
Animal[] anim = new Animal[3];
anim[0] = new dog();
anim[1] = new cat();
anim[2] = new panda();
anim[0].eat();
anim[1].eat();
anim[2].eat();
}
}