C# - 这可能标记被覆盖的方法,最终 [英] C# - is it possible to mark overriden method as final
本文介绍了C# - 这可能标记被覆盖的方法,最终的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C#中,是否有可能重写的虚方法来标记为最终使实施者不能覆盖呢?我将如何做呢?
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() { }
}
有没有办法从覆盖DoAction修改中的B以prevent其他孩子C,无论是在编译时或运行时?
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
}
这篇关于C# - 这可能标记被覆盖的方法,最终的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文