本文介绍了是否可以将重写方法标记为final的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,是否可以将重写的虚拟方法标记为final,因此实现者无法覆盖它?我该怎么做?

In C#, is it possible to mark an overridden virtual method as final so implementers cannot override it? How would I do it?

一个例子可以让它更容易理解:

An example may make it easier to understand:

class A
{
   abstract void DoAction();
}
class B : A
{
   override void DoAction()
   {
       // Implements action in a way that it doesn't make
       // sense for children to override, e.g. by setting private state
       // later operations depend on
   }
}
class C: B
{
   // This would be a bug
   override void DoAction() { }
}

有没有办法修改B为了防止其他子C在编译时或运行时覆盖DoAction?

Is there a way to modify B in order to prevent other children C from overriding DoAction, either at compile-time or runtime?

推荐答案

是的,用密封 :

class A
{
   abstract void DoAction();
}
class B : A
{
   sealed override void DoAction()
   {
       // Implements action in a way that it doesn't make
       // sense for children to override, e.g. by setting private state
       // later operations depend on
   }
}
class C: B
{
   override void DoAction() { } // will not compile
}

这篇关于是否可以将重写方法标记为final的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 03:32