在覆盖方法之前调用C#方法

3

您好, 我有一个基类,其中包含一个需要每个实现都重写的虚拟方法。但是在重写之前,我希望先调用基类方法。 有没有一种方法可以在不实际调用该方法的情况下实现这一点。

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 
    } 
}

我不能总是依赖于在覆盖中调用base.Method(),因此我希望以某种方式强制执行它。这可能是某种设计模式,任何实现结果的方法都可以。


我理解这个例子是为了展示问题,而我提到的解决方案可能完全是另一种方法。 - Francois Taljaard
https://dev59.com/1ovda4cB1Zd3GeqPbZjH#30633107 - Pedro Perez
2个回答

3

一种方式是在基类中定义一个public方法,该方法调用另一个可以被覆盖(或必须被覆盖)的方法:

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
    } 
}

C# 中有“final”关键字吗?我记不得了。 - Zein Makki
已修改为使用 publicprotected - Bathsheba

0

你可以使用装饰器设计模式,应用此模式可以动态地将附加职责附加到对象上。装饰器为扩展功能提供了一种灵活的替代子类化的方法:

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");
    }
}

希望这能帮到你!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接