在C#中,虚方法(Virtual Method)用于在基类中定义一个方法,允许子类对其进行重写(override)。虚方法可以通过关键字virtual来定义,在基类中给出默认的实现,然后在子类中进行重写。
以下是一个简单的示例,演示如何在C#中使用虚方法:
using System;class BaseClass{ public virtual void Print() { Console.WriteLine("This is the base class."); }}class DerivedClass : BaseClass{ public override void Print() { Console.WriteLine("This is the derived class."); }}class Program{ static void Main() { BaseClass baseObj = new BaseClass(); DerivedClass derivedObj = new DerivedClass(); baseObj.Print(); // 输出:This is the base class. derivedObj.Print(); // 输出:This is the derived class. }}在上面的示例中,BaseClass定义了一个虚方法Print(),然后在DerivedClass中重写了这个方法。在Main方法中,我们创建了一个BaseClass对象和一个DerivedClass对象,分别调用了它们的Print()方法,可以看到输出结果分别是基类和派生类的实现。




