假设我有一个名为Animal
的基本抽象类,它有一个名为Move
的虚方法。
我创建了一个名为Mammal
的子类,它继承自Animal并定义了Move
方法。
然后我创建一个名为Mammal
的{{1}}子类。
这就是事情:
我不希望Rabbit
能够覆盖Rabbit
已经定义的Move
的实现({1}}的子类不能更改Move的定义,Mammal
定义的。)
由于Mammal
继承自Mammal
,是否可以“取消虚拟化”Rabbit
类中的Mammal
方法,以防止继承类覆盖方法定义在Move
?
答案 0 :(得分:6)
sealed
When applied to a class, the sealed modifier prevents other classes from inheriting from it. In the following example, class B inherits from class A, but no class can inherit from class B.
You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.
class Animal
{
public virtual void Move() { }
}
class Mammal : Animal
{
public sealed override void Move() { }
}
class Rabbit : Mammal
{
public override void Move() { } // error
}