我有这个:
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派生。
答案 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
所以你需要改变你的设计,以便做一点技巧或解决方法。
Derived1
中定义一种新方法,唯一的工作就是致电base.Connect()
Derived2()
中定义您的Connect()
,它只会调用上一步中定义的上一个函数。检查这个例子:
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();
}
}