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.
相关推荐
c#上位机14 小时前
halcon刚性变换(平移+旋转)——vector_to_rigid
图像处理·人工智能·计算机视觉·c#·halcon
Miss_SQ14 小时前
Webgl打包后删除StreamingAssets文件夹下多余资源
unity·c#·webgl
小猪快跑爱摄影14 小时前
【AutoCad 2025】【C#】零基础教程(二)——遍历 Entity 插件 =》 AutoCAD 核心对象层级结构
开发语言·c#·autocad
烛阴15 小时前
C# Dictionary 入门:用键值对告别低效遍历
前端·c#
Monkey_Xuan18 小时前
C#中的引用传递和值传递
unity·c#
CreasyChan18 小时前
C# LINQ 深度解析:优缺点与性能陷阱
unity·c#·游戏开发
精神小伙就是猛19 小时前
C# sealed密封 追本溯源
开发语言·c#
雨季66620 小时前
C 语言学习指南:从入门到实战的系统路径
c#
缺点内向1 天前
如何在 C# 中创建、读取和更新 Excel 文档
c#·.net·excel
c#上位机1 天前
halcon创建对象数组——concat_obj
图像处理·计算机视觉·c#·halcon