简体   繁体   中英

C# call method before override method

Good day, I have a base class with a virtual method that needs to be overridden per implementation, but I would like to call the base method first before overriding. Is there a way to accomplish this without having to actually call the method.

public class Base
{
    public virtual void Method()
    {
        //doing some stuff here 
    }
}

public class Parent : Base
{
    public override void Method()
    {
        base.Method() //need to be called ALWAYS
        //then I do my thing 
    } 
}

I cannot always rely that the base.Method() will be called in the override, so I would like to enforce it somehow. This might be a design pattern of some kind, any approach to accomplish the result will do.

One way is to define a public method in the base class, which calls another method that can be (or must be) overridden:

public class Base
{
     public void Method()
     {
        // Do some preparatory stuff here, then call a method that might be overridden
        MethodImpl()
     }

     protected virtual void MethodImpl() // Not accessible apart from child classes
     {      
     }
}

public class Parent : Base
{
    protected override void MethodImpl()
    {
       // ToDo - implement to taste
    } 
}

You can use the decorator design pattern, applying this pattern you can attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality:

public abstract class Component
{
    public abstract void Operation();
}

public class ConcreteComponent1 : Component
{
    public override void Operation()
    {
        //logic
    }
}

public abstract class ComponentDecorator : Component
{
    protected readonly Component Component;

    protected ComponentDecorator(Component component)
    {
        Component = component;
    }

    public override void Operation()
    {
        if(Component != null)
            Component.Operation();
    }
}

public class ConcreteDecorator : ComponentDecorator
{
    public ConcreteDecorator(Component component) : base(component)
    {
    }

    public override void Operation()
    {
        base.Operation();
        Console.WriteLine("Extend functionality");
    }
}

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM