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.
相关推荐
一线码农20 分钟前
MinHook 如何对 .NET 母体 CoreCLR 进行拦截
c#·.net·代码注入
小老鼠爱大米3 小时前
[C#] WPF - 资源URI
c#·wpf·uri
阿蒙Amon9 天前
《C#图解教程 第5版》深度推荐
开发语言·c#
暖馒10 天前
C#委托与事件的区别
开发语言·c#
JosieBook10 天前
【C#】C#异步编程:异步延时 vs 阻塞延时深度对比
c#·多线程·异步·阻塞
甄天10 天前
WPF中MVVM和MVVMLight模式
c#·wpf·visual studio
冰茶_10 天前
ASP.NET Core API文档与测试实战指南
后端·学习·http·ui·c#·asp.net
_oP_i10 天前
实现 “WebView2 获取word选中内容
开发语言·c#·word
Kookoos10 天前
ABP vNext + Azure Application Insights:APM 监控与性能诊断最佳实践
后端·c#·.net·abp vnext
专注VB编程开发20年10 天前
asp.net core Razor动态语言编程代替asp.net .aspx更高级吗?
开发语言·后端·c#·asp.net·.net