Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 多态

作者:炼狱死神   发布日期:2026-04-06   浏览:86

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();
        }
    }
}

解释说明:

  1. 基类 Animal:定义了一个虚方法 MakeSound(),允许派生类重写该方法。
  2. 派生类 DogCat:分别重写了 MakeSound() 方法,提供了各自特有的实现。
  3. 多态性:通过基类引用(如 Animal myDog = new Dog();),可以在运行时调用派生类的具体实现。这样可以实现代码的灵活性和扩展性。
  4. 数组示例:展示了如何使用多态性在一个数组中存储不同类型的对象,并调用它们的方法。

这段代码演示了 C# 中的多态特性,即同一方法在不同对象上调用时表现出不同的行为。

上一篇:c# byte转int

下一篇:c#窗体大小不允许调整的属性

大家都在看

c# 二进制

c# 创建目录

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站