C#: Any way to skip over one of the base calls in polymorphism?

后端 未结 7 1370
一个人的身影
一个人的身影 2021-01-17 16:34
class GrandParent
{
    public virtual void Foo() { ... }
}

class Parent : GrandParent
{
    public override void Foo()
    {
       base.Foo();

       //Do additi         


        
7条回答
  •  庸人自扰
    2021-01-17 16:52

    Your design is wrong if you need this.
    Instead, put the per-class logic in DoFoo and don't call base.DoFoo when you don't need to.

    class GrandParent
    {
        public void Foo()
        {
            // base logic that should always run here:
            // ...
    
            this.DoFoo(); // call derived logic
        }
    
        protected virtual void DoFoo() { }
    }
    
    class Parent : GrandParent
    {
        protected override void DoFoo()
        {    
           // Do additional work (no need to call base.DoFoo)
        }
    }
    
    class Child : Parent
    {
        protected override void DoFoo()
        {  
            // Do additional work (no need to call base.DoFoo)
        }
    }
    

提交回复
热议问题