惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

阮一峰的网络日志
阮一峰的网络日志
Blog — PlanetScale
Blog — PlanetScale
B
Blog RSS Feed
L
LangChain Blog
Jina AI
Jina AI
爱范儿
爱范儿
C
Check Point Blog
云风的 BLOG
云风的 BLOG
Last Week in AI
Last Week in AI
月光博客
月光博客
GbyAI
GbyAI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Stack Overflow Blog
Stack Overflow Blog
V
V2EX
A
About on SuperTechFans
有赞技术团队
有赞技术团队
Microsoft Azure Blog
Microsoft Azure Blog
The GitHub Blog
The GitHub Blog
博客园 - Franky
Apple Machine Learning Research
Apple Machine Learning Research
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
博客园 - 三生石上(FineUI控件)
S
SegmentFault 最新的问题

博客园 - 言午

Nopcommerce 二次开发2 Admin Nopcommerce 二次开发1 基础 Nopcommerce 二次开发2 WEB Nopcommerce 二次开发0 sqlce中不支持sp_rename修改表名 C#读取Excel遇到无法读取的解决方法 狼奔代码生成器 银行账户类 累 interface 抽象类 抽象方法 Message 类的继承 事件event 委托 代理 索引! 第五周作业 第四周作业 考试! 线程安全 二 线程安全 一
多态(虚方法)
言午 · 2012-04-11 · via 博客园 - 言午

使用虚方法实现“多态”

背景:

    

class Animal
    {
        public string name; public int age; public float temperature;
        public  void Eat()
        {
            Console.WriteLine("Animal 吃东西");
        }
    }
    class Wolf : Animal
    {
        public string color;
        public void hunt(){}
        public  void Eat()
        {
            Console.WriteLine("Wolf 吃 羊");
        }
    }
    class Fish:Animal
    {       
        public void Swim() { }
        public void Eat()
        {
            Console.WriteLine("Fish 吃东西 小Fish");
        }
    }   

在main方法中使用这段代码

            Wolf hui = new Wolf();
            hui.Eat();
           
            Fish jin = new Fish();
            jin.Eat();

发现,使用的Eat方法都是派生类的。

但是,如果这样使用

            Animal a;
            a = hui;           
            a.Eat();   

            a = jin;            
            a.Eat();

使用的Eat方法,却是基类的!!!

这显然不是我们想要的。

我们需要,根据对象运行时,所属类的不同,调用相应类的方法。

这就是多态

关键词 virtual  override。在基类中的方法,加上修饰符virtual ,在派生类中加上override 。代码如下:

    

class Animal
    {
        public string name; public int age; public float temperature;
        public virtual  void Eat()
        {
            Console.WriteLine("Animal 吃东西");
        }
    }
    class Wolf : Animal
    {
        public string color;
        public void hunt(){}
        public override void Eat()
        {
            Console.WriteLine("Wolf 吃 羊");
        }
    }
    class Fish:Animal
    {       
        public void Swim() { }
        public override void Eat()
        {
            Console.WriteLine("Fish 吃东西 小Fish");
        }
    }   

再看看程序运行的结果