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.
相关推荐
烛阴19 分钟前
C#常量(const)与枚举(enum)使用指南
前端·c#
阿Y加油吧2 小时前
java并发编程面试题精讲——day02
java·面试·c#
唐青枫2 小时前
C#.NET DateTime 最强入门到进阶:格式化、转换、UTC、时区全覆盖
c#·.net
葛小白117 小时前
C#进阶13:C#全局路径规划算法_A*
c#·路径规划算法·astar算法
时光追逐者20 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 61 期(2025年11.10-11.16)
c#·.net·.netcore
世洋Blog1 天前
Unity面经-List底层原理、如何基于数组、如何扩容、List存储泛型、List有关在内存中的结构
unity·面试·c#·list
PfCoder1 天前
C# async / await 用法以及和Task的关系
c#·多线程·winform·async、await
唐青枫1 天前
.NET Web 应用 Linux 部署全指南:从环境搭建到生产上线
c#·.net