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.
相关推荐
by__csdn10 小时前
第一章 (ASP.NET Core入门)第三节( 认识.NET Standard)
后端·c#·asp.net·.net·.netcore·f#·vb.net
12332111122211 小时前
Listbox DataTemplate
c#
夏霞11 小时前
c# ActiveMQ
开发语言·c#·activemq
她说彩礼65万12 小时前
C# ConcurrentDictionary详解
java·服务器·c#
DataIntel12 小时前
WPF 中的数据模板(DataTemplate)与样式/控件模板(Style / ControlTemplate)详解
c#
by__csdn12 小时前
第一章 (ASP.NET Core入门)第一节( 认识.NET Core)
后端·c#·asp.net·.net·.netcore·f#·vb.net
by__csdn12 小时前
第一章 (ASP.NET Core入门)第二节( 认识ASP.NET Core)
数据库·后端·c#·asp.net·.net·.netcore·f#
缺点内向12 小时前
如何使用C#将Excel工作表拆分为独立文件
开发语言·c#·.net·excel
CodeCraft Studio13 小时前
Excel处理控件Aspose.Cells教程:使用 C# 在 Excel 中创建股票高低收盘图
信息可视化·c#·excel·aspose·股票收盘图·c# excel库·收盘图
秋月的私语13 小时前
c#字符串Split与CSV解析中的引号处理
服务器·开发语言·c#