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

问题描述:

美好的一天, 我有一个虚拟方法,每个实现需要重写的虚拟方法,但我希望在覆盖之前先调用基方法。 有没有办法实现这一点,而不必实际调用方法。覆盖方法之前的C#调用方法

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()将在override中被调用,所以我想以某种方式强制它。这可能是某种设计模式,任何完成结果的方法都可以。

+0

,我理解的例子是显示问题和解决方案就像我提到的可能是一个不同的方法一起 –

+0

http://*.com/a/30633107/2920197 –

的一种方法是定义在基类中的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 
    } 
} 
+0

我们有一个'在final'关键词C# ?我不记得那个。 – user3185569

+0

@ user3185569:修改为使用“public”和“protected”。 – Bathsheba

+0

@Bathsheba thx我实际上使用保护。好的解决方案 –

您可以使用装饰设计模式,采用这种模式,你可以动态地将额外的责任附加到对象上。装饰提供了一个灵活的选择子类的扩展功能:

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

希望这有助于!