C#多态--虚方法实现多态
时间: 2023-07-19 07:20:12 浏览: 80
在C#中,多态是指在不同的情况下,同一个方法名可以具有不同的行为。实现多态的一种常见方式是使用虚方法。
在C#中,通过在父类中声明一个虚方法,在子类中覆盖该方法并实现不同的行为。当我们调用该方法时,实际执行的是子类中的方法。
下面是一个简单的例子:
```
class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("The cat meows");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("The dog barks");
}
}
class Program
{
static void Main(string[] args)
{
Animal animal1 = new Animal();
Animal animal2 = new Cat();
Animal animal3 = new Dog();
animal1.MakeSound();
animal2.MakeSound();
animal3.MakeSound();
}
}
```
在上面的例子中,我们声明了一个基类`Animal`,其中包含一个虚方法`MakeSound()`。然后我们创建了两个子类`Cat`和`Dog`,并且覆盖了基类中的`MakeSound()`方法。最后在主函数中,我们分别创建了一个基类对象和两个子类对象,并且调用了它们的`MakeSound()`方法。
运行程序后,输出结果如下:
```
The animal makes a sound
The cat meows
The dog barks
```
可以看到,当我们调用`MakeSound()`方法时,实际执行的是该对象的子类中的方法。这就是多态的实现方式之一。