using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VirtualFunc
{
class Animal
{
//虚函数Shout()
public virtual void Shout()
{
System.Console.WriteLine("Animal.Shout()......");
}
//虚函数Run()
public virtual void Run()
{
System.Console.WriteLine("Animal.Run()......");
}
//虚函数Walk()
public virtual void Walk( )
{
System.Console.WriteLine("Animal.Walk()......");
}
}
class Dog : Animal
{
//重写Animal.Shout()
public override void Shout( )
{
System.Console.WriteLine("Dog.Shout()......");
}
//重写Animal.Run()
public override void Run( )
{
System.Console.WriteLine("Dog.Run()......");
}
//重写Animal.Walk()
public new void Walk( )
{
System.Console.WriteLine("Dog.Walk()......");
base.Walk( ); //显式调用父类的实现
}
}
class HaBaDog : Dog
{
//重写Dog.Shout()
public override void Shout( )
{
System.Console.WriteLine("HaBaDog.Shout()......");
}
}
class Program
{
static void Main(string[] args)
{
//演示Animal的虚函数调用
System.Console.WriteLine("1---------Animal------------1");
Animal aml1 = new Animal( );
aml1.Shout( );
aml1.Run( );
//演示Dog的虚函数调用
System.Console.WriteLine("2---------Dog---------------2");
Animal aml2 = new Dog( );
aml2.Shout( );
aml2.Run( );
//演示HaBaDog的虚函数调用
System.Console.WriteLine("3---------HaBaDog-----------3");
Animal aml3 = new HaBaDog( );
aml3.Shout( );
aml3.Run( );
//演示base在虚函数中的使用
System.Console.WriteLine("4---------Dog.Walk()--------4");
aml2.Walk( );
Dog adog = (Dog) aml2;
adog.Walk( );
Console.ReadKey();
}
}
}
从这个例子里我没有看到虚函数存在的意义,可能是我对虚函数的理解还不够到位!