例子展示:
设置一个动物类,dog类,cat类,使用虚方法改写
点击查看代码
using System;
public class Animal
{
// 声明一个虚方法
public virtual void Speak()
{
Console.WriteLine("Animal speaks");
}
}
public class Dog : Animal
{
// 重写基类的虚方法
public override void Speak()
{
Console.WriteLine("Dog barks");
}
}
public class Cat : Animal
{
// 重写基类的虚方法
public override void Speak()
{
Console.WriteLine("Cat meows");
}
}
public class Program
{
public static void Main()
{
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();
myAnimal.Speak(); // 输出: Animal speaks
myDog.Speak(); // 输出: Dog barks
myCat.Speak(); // 输出: Cat meows
}
}