c#实现多态(一) : virtual 函数 实现

来源:互联网 发布:手机淘宝卖话费充值 编辑:程序博客网 时间:2024/05/29 09:20

 一  实现多态的条件:

1 继承 

2  父类中有虚函数,子类里需要override 父类的虚函数

3 子类对象赋值给父类对象


二   显示效果




三  代码

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Xml;namespace CsharpConsoleApplication{    class Program    {        static void Main(string[] args)        {            BaseAction action = new BaseAction();            action.process("父类");            action = new GetPatientInfo();  //子类对象赋值给父类 实现多态            action.process("获取病人信息");  //虽然是父类( BaseAction )对象,但是调用子类( GetPatientInfo )的方法            action = new GetDeptmentInfo();  //子类对象赋值给父类 实现多态            action.process("获取科室信息");  //虽然是父类( BaseAction )对象,但是调用子类( GetDeptmentInfo )的方法            System.Console.ReadLine();        }        class BaseAction        {            public virtual void process(string ActionCode) //虚函数            {                System.Console.WriteLine(ActionCode +" : BaseAction 类的 process 函数");            }        }        //获取病人信息类        class GetPatientInfo :BaseAction //继承父类        {            public override void process(string ActionCode)            {                System.Console.WriteLine(ActionCode + " : GetPatientInfo类的process函数");            }        }        //获取科室信息类        class GetDeptmentInfo : BaseAction        {            public override void process(string ActionCode)            {                System.Console.WriteLine(ActionCode + " : GetDeptmentInfo类的process函数");            }        }    }   }


0 0
原创粉丝点击