停止在抽象中继承方法

Stop inherit method in abstraction

我有一个摘要 class 继承了它。在 parent 方法中,我检查了一些条件,如果它们发生,Child 方法应该停止 运行。但是在 return 之后 child 继续它的代码!这些方法应该是无效的。 我也试过 throw new Exception(); 但没有用。

public abstract class ParentClass
{
    public virtual void Method()
    {
        if (true)
        {
            // do something
            Console.WriteLine("Parent Method should stop it's child!");
            return; /* So the child should be stopped to call it's things*/
           // Also checked by throw exception.
        }
    }
}

并且在ChildClass

public class ChildClass :ParentClass
{
    public override void Method()
    {
        base.Method(); // Also checked by try/catch
        Console.WriteLine("Should't be run");
    }
}

那么我该怎么做呢(parent 控制 child 进程是否继续)?

如果我们将方法签名更改为 布尔值,您可以这样做:

class ParentClass
{
    public virtual bool Method()
    {
        return false;
    }
}

class ChildClass : ParentClass
{
    public override bool Method()
    {
        var toContinue = base.Method();
        if (!toContinue)
        {
            return false;
        }

        //Continue..

        return true;
    }
}

我想你要找的是 "Template Method":

public abstract class ParentClass
{
    public void Method()
    {
        FirstOperation();
        if ( .. some condition ..)
        {
            SecondOperation();
            // do something
            Console.WriteLine("Parent Method should stop it's child!");
        }
        else
        {
            ThirdOperation();
        }
    }

    protected abstract void FirstOperation();
    protected abstract void SecondOperation();
    protected abstract void ThirdOperation();
}


public class ChildClass :ParentClass
{
    protected override void FirstOperation();
    {

    }

    protected override void SecondOperation();
    {

    }

    protected override void ThirdOperation();
    {

    }
}

这样您就可以控制来自父对象的流程,而只需在子对象中调用您需要的方法。

需要说的是,按照你现在的方式去做是非常糟糕的设计决定,但如果你真的需要那样做的话

public abstract class ParentClass
{
    public virtual void Method()
    {
        if (true)
        {
            // do something
            Console.WriteLine("Parent Method should stop it's child!");
            throw new Exception();
        }
    }
}

public class ChildClass : ParentClass
{
    public override void Method()
    {
        try
        {
            base.Method();
        }
        catch (Exception)
        {
            return;
        }
        Console.WriteLine("Should't be run");
    }
}