注入继承

时间:2015-05-25 21:56:54

标签: c# inheritance

是否可以在继承的类中重新调用调用,在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;
}

1 个答案:

答案 0 :(得分:4)

您可以使用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);,我们会收到此订单:

  1. TheBaseClass.CallTheProcess
  2. TheFirstClass.Process
  3. TheLastClass.Process(//other operations部分)