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

时间:2009-04-28 12:02:53

标签: c# .net 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() { }
}

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

4 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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
}

答案 2 :(得分:6)

你需要“密封”。

答案 3 :(得分:5)

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

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