C# 是否可以将重写的方法标记为 final

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/797530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:33:48  来源:igfitidea点击:

is it possible to mark overridden method as final

c#.netinheritance

提问by dbkk

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

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

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() { }
}

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

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

采纳答案by Lucero

Yes, with "sealed":

是的,用“密封”:

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
}

回答by RichieHindle

You need "sealed".

你需要“密封”。

回答by Ryan Emerle

You can mark the method as sealed.

您可以将该方法标记为sealed.

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

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 - 'C.F()': cannot override 
                                // inherited member 'B.F()' because it is sealed
}

回答by serg10

Individual methods can be marked as sealed, which is broadly equivalent to marking a method as final in java. So in your example you would have:

可以将单个方法标记为sealed,这大致相当于在java 中将方法标记为final。因此,在您的示例中,您将拥有:

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