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(); } } }
从这个例子里我没有看到虚函数存在的意义,可能是我对虚函数的理解还不够到位!
相关文章推荐
- C#正则表达式合并连续空格为单个空格
- [C#]读文件
- C#基础知识之静态成员
- C#如何遍历Dictionary
- C#基础知识之函数重载OverLoad
- C# 访问控制符 0006
- C#反转字符串
- C#操作读取、写入XML文档的实用方法
- C#基础知识之interface
- c#封装
- C#获取文件的MD5码
- C#实现在控制台输入密码显示星号的方法
- c#Reverse字符串
- c#获取数组中指定元素的索引
- c#获取数组中最大的元素
- C#中考虑为大对象使用弱引用
- C# WinForm 添加Windows Media Player 控件调试出现未能加载文件或程序集Interop.WMPLib,该怎么解决
- C# winform socket一个服务端和多个客户端进行通信
- C# Console.WriteLine()函数中{}输出格式详解
- c# 扩展方法奇思妙用变态篇二:封装 if/else、swith/case 及 while