is it possible to mark overridden method as final

前端 未结 4 1522
慢半拍i
慢半拍i 2020-12-14 05:49

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 understan

相关标签:
4条回答
  • 2020-12-14 06:16

    You can mark the method as 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
    }
    
    0 讨论(0)
  • 2020-12-14 06:19

    You need "sealed".

    0 讨论(0)
  • 2020-12-14 06:24

    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
    }
    
    0 讨论(0)
  • 2020-12-14 06:29

    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:

    class B : A
    {
      override sealed void DoAction()
      {
        // implementation
      }
    }
    
    0 讨论(0)
提交回复
热议问题