这是一个动物园的动物发出不同的声音,使用了继承和多态
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.