您的位置:首页 > 编程语言 > C#

C#基础知识之虚函数

2016-04-21 14:39 399 查看
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();

}
}
}


从这个例子里我没有看到虚函数存在的意义,可能是我对虚函数的理解还不够到位!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: