Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
206 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...