是否可以在继承的类中重新定义调用的用途,所以我需要在TheFirstClass处理上下文之前和之后对TheLastClass中的上下文做一些其他操作。理想情况下,我不想在所有TheLastClass实例中都重命名进程覆盖。我试图添加另一个抽象类,但是继承阻止了另一个同名抽象类。

void Main()
{
    var context = new ContextClass();
    var LastClass = new TheLastClass();
    LastClass.CallTheProcess(context);
}

// Define other methods and classes here
abstract class TheBaseClass
{
    public abstract void Process(ContextClass context);

    public void CallTheProcess(ContextClass context)
    {
        // other necessary stuff
        context.test = "Base Class";
        Process(context);
    }
}

class TheFirstClass : TheBaseClass
{
    //public abstract void Process(ContextClass context)
    public override void Process(ContextClass context)
    {
        context.test = "success";
        Process(context);//How can I call inherited overrides? and not infinite loop
    }
}

class TheLastClass : TheFirstClass
{
    public override void Process(ContextClass context)
    {
        //do stuff with the context
        if(context.test == "success")
        {
            "ThisWorked".Dump();
            //how do I get here?
        }
    }
}

class ContextClass
{
    public string test;
}

最佳答案

您可以使用base关键字。

void Main()
{
    var context = new ContextClass();
    var LastClass = new TheLastClass();
    LastClass.CallTheProcess(context);
}


abstract class TheBaseClass
{
    public abstract void Process(ContextClass context);

    public void CallTheProcess(ContextClass context)
    {
        this.Process(context);
        // other necessary stuff
        context.test = "Base Class";
    }
}

class TheFirstClass : TheBaseClass
{
    public override void Process(ContextClass context)
    {
        context.test = "success";
        // some operations
    }
}

class TheLastClass : TheFirstClass
{
    public override void Process(ContextClass context)
    {
        base.Process(context); // from the TheFirstClass
        // other operations
    }
}


然后,如果您致电LastClass.CallTheProcess(context);,您将获得以下命令:


TheBaseClass.CallTheProcess
FirstClass.Process
TheLastClass.Process(//other operations部分)

10-06 04:18