使子类无法覆盖方法实现

时间:2016-04-21 21:47:01

标签: c# .net inheritance

假设我有一个名为Animal的基本抽象类,它有一个名为Move的虚方法。

我创建了一个名为Mammal的子类,它继承自Animal并定义了Move方法。

然后我创建一个名为Mammal的{​​{1}}子类。

这就是事情:

我不希望Rabbit能够覆盖Rabbit已经定义的Move的实现({1}}的子类不能更改Move的定义,Mammal定义的。)

由于Mammal继承自Mammal,是否可以“取消虚拟化”Rabbit类中的Mammal方法,以防止继承类覆盖方法定义在Move

1 个答案:

答案 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
}
相关问题