是否有可能让覆盖方法调用其抽象虚方法?

时间:2017-11-15 23:01:57

标签: c# override virtual abstract

我的目标是在其中一个派生类上调用Consume后自行更新Abstract类。

想象一下:

public interface IConsumable 
{
    void Consume();
}

public abstract class AbstractConsumable : IConsumable
{
    private bool _consumed = false;

    public virtual void Consume()
    {
        _consumed = true;
    }
}

public class HealthyConsumable: AbstractConsumable
{
    public override void Consume()
    {
        // Do something healthy and ...
        base.Consume(); // Would like to avoid this...
    }
}

public class PoisonousConsumable: AbstractConsumable
{
    public override void Consume()
    {
        // Do something poisonous and ...
        base.Consume(); // Would like to avoid this...
    }
}

我想在这里实现的是不必在base.Consume()方法上调用override,但是一旦派生类调用它们{{1},它仍然具有抽象类集_consumed方法。

2 个答案:

答案 0 :(得分:1)

您可以使Consume none虚拟,并在其中调用另一个受保护的虚拟(或抽象方法),该虚拟(或抽象方法)可以包含由子类更改的代码。您的类的消费者只能调用公共Consume方法,但这将实习调用子类实现特定代码

public interface IConsumable 
{
    void Consume();
}

public abstract class AbstractConsumable : IConsumable
{
    private bool _consumed = false;

    public void Consume()
    {
        _consumed = true;
        InternalConsumerBehaviour();
    }

    protected virtual void InternalConsumeBehaviour()
    {
         //default do nothing could potentially mark this method abstract rather than virtual its up to you
    }
}

public class HealthyConsumable: AbstractConsumable
{
    protected override void InternalConsumeBehaviour()
    {
        // Do something healthy and ...
    }
}

public class PoisonousConsumable: AbstractConsumable
{
    protected override void InternalConsumeBehaviour()
    {
        // Do something poisonous and ...
    }
}

答案 1 :(得分:1)

如果我得到你正确的要求,你可以做这样的事情:

public interface IConsumable 
{
    void Consume();
}

public abstract class AbstractConsumable : IConsumable
{
    private bool _consumed = false;

    public abstract void ConsumeEffects();

    public void Consume()
    {
        this.ConsumeEffects();
        _consumed = true;
    }
}

public class HealthyConsumable: AbstractConsumable
{
    public override void ConsumeEffects()
    {
        // Do something healthy and ...
        // Consume will get called in the base
    }
}

public class PoisonousConsumable: AbstractConsumable
{
    public override void ConsumeEffects()
    {
        // Do something poisonous and ...
        // Consume will get called in the base
    }
}