一、基本介绍
虚函数(Virtual Function)和重写(Override)是面向对象编程中多态性的重要概念。它们允许子类改变继承自父类的行为。
虚函数
虚函数是可以在派生类中被重写的函数。在基类中声明虚函数时,使用关键字 virtual
。这样,派生类可以使用 override
关键字来提供新的实现。
虚函数的声明
public class Animal
{public virtual void MakeSound(){Console.WriteLine("Some sound");}
}
重写
重写是派生类提供与基类中虚函数具有相同名称和签名的方法的过程。在派生类中重写基类的方法时,使用关键字 override
。
重写的声明
public class Dog : Animal
{public override void MakeSound(){Console.WriteLine("Bark");}
}
抽象类和抽象方法
抽象类是不能被实例化的类,它通常包含一个或多个抽象方法。抽象方法是没有实现的方法,它只有声明,没有方法体,使用 abstract
关键字声明。
抽象类的声明
public class Dog : Animal
{public override void MakeSound(){Console.WriteLine("Bark");}
}
密封类和密封方法
有时候,你可能不希望派生类能够重写基类的方法。在这种情况下,可以使用 sealed
关键字来阻止方法被重写。
密封方法的声明
public class Animal
{public virtual void MakeSound(){Console.WriteLine("Some sound");}public sealed void Eat(){Console.WriteLine("Eating");}
}
尝试重写密封方法
public class Dog : Animal
{public override void MakeSound(){Console.WriteLine("Bark");}// 下面的代码将导致编译错误,因为 Eat 方法被密封了// public override void Eat()// {// Console.WriteLine("Eating differently");// }
}
使用虚函数和重写的示例
public class Program
{public static void Main(){Animal myAnimal = new Dog();myAnimal.MakeSound(); // 输出 "Bark"Animal myOtherAnimal = new Animal();myOtherAnimal.MakeSound(); // 输出 "Some sound"Dog myDog = new Dog();myDog.Eat(); // 输出 "Eating",Eat 方法被密封,无法重写}
}public abstract class Animal
{public abstract void MakeSound();public sealed void Eat(){Console.WriteLine("Eating");}
}public class Dog : Animal
{public override void MakeSound(){Console.WriteLine("Bark");}
}