从派生的派生类调用父类方法

时间:2013-06-19 16:26:19

标签: c#

我有这个:

public class Base {
   public virtual void Connect()
   {
      // do stuff
   }
}

public class Derived1 : Base {
   public override void Connect()
   {
       base.Connect();
      // do other stuff
   }
}

public class Derived2 : Derived {
   public override void Connect()
   {
      base.Connect() // Here I want to call Base::Connect(), not Derived::Connect()
   }
}

有没有办法可以从Derived2调用Base :: Connect,因为我想跳过Derived1 :: Connect()中的“do other stuff”部分?

编辑:我必须从Derived1派生。

2 个答案:

答案 0 :(得分:3)

Yo可以尝试将Connect拆分为两个函数,并从需要它的所有派生类中调用DoConnect

public class Base {
   public virtual void Connect()
   {
      DoConnect();
   }

   protected void DoConnect()
   {
      // do stuff
   }
}

...

public class Derived2 : Derived1 {
   public override void Connect()
   {
      DoConnect();
      ...
   }
}

如果您无法更新基类,则可以在Derived1

执行此拆分
public class Derived1 : Base {
   public virtual void Connect()
   {
      DoConnect();
   }

   protected void DoConnect()
   {
      base.Connect();
   }
}

答案 1 :(得分:1)

C#剂量没有提供直接的方式来调用base.base.method()首先需要更改您的设计 请查看此答案why-c-sharp-doesnt-support-base-base

所以你需要改变你的设计,以便做一点技巧或解决方法。

  1. 在班级Derived1中定义一种新方法,唯一的工作就是致电base.Connect()
  2. 然后在您的班级Derived2()中定义您的Connect(),它只会调用上一步中定义的上一个函数。
  3. 检查这个例子:

    public class Base {
        public virtual void Connect() {
            // do stuff
        }
    }
    
    public class Derived1: Base {
        public override void Connect() {
            base.Connect();
            // do other stuff
        }
        public void CallBaseConnnect() {
            //here make only one call to base.Connect(). 
            //that's how class Derived1 'll provide you away to call base.Connect().
            base.Connect();
        }
    }
    
    public class Derived2: Derived {
        public override void Connect() {
            //here just make a call to CallBaseConnnect() in base class Derived1
            //that 'll equivalent to base.base.Connect.
            base.CallBaseConnnect();
        }
    }