是否有可能将重写的方法标记为final

在C#中,是否有可能将重写的虚拟方法标记为final,以便实现者不能重写它? 我该怎么做?

一个例子可能会让人更容易理解:

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, eg by setting private state // later operations depend on } } class C: B { // This would be a bug override void DoAction() { } } 

有没有办法修改B,以防止其他孩子C在编译时或运行时重写DoAction?

是的,用“密封”:

 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, eg by setting private state // later operations depend on } } class C: B { override void DoAction() { } // will not compile } 

您可以将该方法标记为sealed

http://msdn.microsoft.com/en-us/library/aa645769(VS.71).aspx

 class A { public virtual void F() { } } class B : A { public sealed override void F() { } } class C : B { public override void F() { } // Compilation error - 'CF()': cannot override // inherited member 'BF()' because it is sealed } 

你需要“密封”。

单独的方法可以被标记为密封,这大致等同于在java中将方法标记为final。 所以在你的例子中你会有:

 class B : A { override sealed void DoAction() { // implementation } }