13.继承和多态的实例 C#

这是一个动物园的动物发出不同的声音,使用了继承和多态

cs 复制代码
using System;
using System.Collections.Generic;

namespace InheritanceAndPolymorphismExample
{
    //一个动物类,包含属性:名称。包含方法:发出叫声
    public class Animal
    {
        public string Name { get; set; }
        public virtual void Speak()
        {
            Console.WriteLine("The animal makes a sound.");

        }
    }

    //从动物类继承一个狗类,多态一个方法:狗叫
    public class Dog : Animal
    {
        public override void Speak()
        {
            Console.WriteLine("The dog says:Woof!");

        }
    }

    //从动物类继承一个猫类,多态一个方法:猫叫
    public class Cat : Animal
    {


        public override void Speak()
        {
            Console.WriteLine("The cat says:Meow!");

        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //新建一个列表,叫动物们,对应的是animal类,并引入实例,狗猫动物
            List<Animal> animals = new List<Animal>
            {

                new Dog{Name="Buddy" },
                new Cat{Name="Whiskers"},
                new Animal{Name="Generic Animal" }

            };

            //从列表中读取,全部执行方法
            foreach (Animal animal in animals)
            {
                Console.WriteLine($"Animal:{animal.Name}");
                animal.Speak();
                Console.WriteLine();


            }
            Console.ReadLine();

        }
    }




}

输出结果:

cs 复制代码
The animal:Leo
The cat says:Meow!

The animal:Whiskers
The dog says:Woof!

The animal:Generic Animal
The Animal makes a sound.
相关推荐
观无1 小时前
c#中的virtual方法
开发语言·c#
code bean2 小时前
【C#】ForEach vs foreach
开发语言·c#
OpenSeek3 小时前
【设计模式】面向对象的设计模式概述
设计模式·c#·设计原则
码观天工4 小时前
10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析
c#·.net·继承·思维·面相对象
FAREWELL0007515 小时前
C#核心学习(一)面向过程与面向对象编程---初识类和对象
学习·c#·面向对象
yngsqq16 小时前
Visual Studio中创建和配置设置文件(Settings.settings) - 详细步骤指南——待调试
c#
DanmF--18 小时前
用C#实现UDP服务器
服务器·网络协议·udp·c#
观无18 小时前
.NET开发基础知识1-10
c#
且听风吟ayan19 小时前
leetcode day33 738+343
leetcode·c#
Tatalaluola20 小时前
【Unity】 鼠标拖动物体移动速度跟不上鼠标,会掉落
学习·unity·c#·游戏引擎