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.
相关推荐
阿蒙Amon6 分钟前
C#每日面试题-Thread.Sleep和Task.Delay的区别
java·数据库·c#
cfqq19891 小时前
Settings,变量保存
开发语言·c#
云草桑2 小时前
.net AI开发04 第八章 引入RAG知识库与文档管理核心能力及事件总线
数据库·人工智能·microsoft·c#·asp.net·.net·rag
曹牧4 小时前
C#:窗体构造函数无法引用窗体控件
开发语言·c#
iAkuya4 小时前
(leetcode)力扣100 54实现Trie树
算法·leetcode·c#
xb11324 小时前
C#使用Cancellation来取消异步任务
开发语言·c#
m0_748229994 小时前
C与C#:编程语言的核心差异解析
c语言·开发语言·c#
m0_748229995 小时前
Laravel7.x核心特性全解析
c语言·数据库·c#
阿蒙Amon5 小时前
C#每日面试题-Task和Thread的区别
java·面试·c#
ytttr8737 小时前
C#实现海康威视智能车牌识别
开发语言·c#