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

dbk*_*bkk 45 .net c# inheritance

在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, e.g. by setting private state
       // later operations depend on  
   }
}
class C: B
{
   // This would be a bug
   override void DoAction() { }
}
Run Code Online (Sandbox Code Playgroud)

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

Luc*_*ero 73

是的,"密封":

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
}
Run Code Online (Sandbox Code Playgroud)


Rya*_*rle 8

您可以将方法标记为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 - 'C.F()': cannot override 
                                // inherited member 'B.F()' because it is sealed
}
Run Code Online (Sandbox Code Playgroud)


Ric*_*dle 6

你需要"密封".


ser*_*g10 5

各个方法可以标记为已密封,这大致相当于在java中将方法标记为final.所以在你的例子中你会有:

class B : A
{
  override sealed void DoAction()
  {
    // implementation
  }
}
Run Code Online (Sandbox Code Playgroud)