using System;
public class Animal
{
// 定义一个虚方法,允许派生类重写该方法
public virtual void MakeSound()
{
Console.WriteLine("This animal makes a sound.");
}
}
public class Dog : Animal
{
// 重写基类中的虚方法
public override void MakeSound()
{
Console.WriteLine("The dog barks.");
}
}
public class Program
{
public static void Main()
{
Animal myAnimal = new Animal();
Animal myDog = new Dog();
myAnimal.MakeSound(); // 输出: This animal makes a sound.
myDog.MakeSound(); // 输出: The dog barks.
}
}
virtual 关键字用于声明一个可以被派生类重写的方法。Animal 类定义了一个虚方法 MakeSound,它可以在派生类中被重写。Dog 类继承自 Animal 并重写了 MakeSound 方法。Animal 类型的引用调用 MakeSound 方法时,实际执行的方法取决于对象的实际类型。如果对象是 Dog 类型,则会调用 Dog 类中重写的版本。上一篇:c#向下取整
下一篇:c# 数组合并
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站