using System;
// 定义一个基类
public class Animal
{
// 基类中的虚方法,允许派生类重写
public virtual void MakeSound()
{
Console.WriteLine("This animal makes a sound.");
}
}
// 派生类1
public class Dog : Animal
{
// 重写基类的虚方法
public override void MakeSound()
{
Console.WriteLine("Dog barks: Woof woof!");
}
}
// 派生类2
public class Cat : Animal
{
// 重写基类的虚方法
public override void MakeSound()
{
Console.WriteLine("Cat meows: Meow meow!");
}
}
class Program
{
static void Main(string[] args)
{
// 创建基类引用,指向不同派生类的对象
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();
// 调用多态方法
myAnimal.MakeSound(); // 输出: This animal makes a sound.
myDog.MakeSound(); // 输出: Dog barks: Woof woof!
myCat.MakeSound(); // 输出: Cat meows: Meow meow!
// 使用数组存储不同类型的对象,并调用多态方法
Animal[] animals = { myAnimal, myDog, myCat };
foreach (Animal animal in animals)
{
animal.MakeSound();
}
}
}
Animal:定义了一个虚方法 MakeSound(),允许派生类重写该方法。Dog 和 Cat:分别重写了 MakeSound() 方法,提供了各自特有的实现。Animal myDog = new Dog();),可以在运行时调用派生类的具体实现。这样可以实现代码的灵活性和扩展性。这段代码演示了 C# 中的多态特性,即同一方法在不同对象上调用时表现出不同的行为。
上一篇:c# byte转int
下一篇:c#窗体大小不允许调整的属性
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站