我怎样才能做到这一点:我可以从基类调用孩子的父方法吗?
class BaseClass{
void templateMethod(){
methodImplementation();
if(this.base.getType() != typeof(BaseClass)) this.base.methodImplementation();
}
void abstract methodImplementation();
}
class Derived1 : BaseClass{
void override methodImplementation(){
.. do things ..
}
}
class Derived2 : Derived1{
void override methodImplementation(){
.. do more things ..
}
}
那么这将导致两个实现(的东西,更多的东西)执行。
Derived2 object = new Derived2();
object.templateMethod();
然后,所有的孩子和孙子女等等,只需要实现自己的methodImplementation的一部分,并在最后的对象调用时它会被调用在所有水平。
但是this.base不是一件东西。我需要的是调用实例化对象真实类的父对象的实现,但代码位于baseClass中,因此我可以在Template方法模式中使用它。
在此先感谢,抱歉,如果我没有让自己清楚。我只需要知道它是否可以完成。这是良好的做法,最佳,推荐或有用的是我会考虑的另一件事。
编辑:
上面的代码是不完全正确的,它应该是这样的:
class BaseClass{
void templateMethod(){
methodImplementation();
if(this.base.getType() != typeof(BaseClass)) this.base.templateMethod();
}
void abstract methodImplementation();
}
class Derived1 : BaseClass{
void override methodImplementation(){
.. do things ..
}
}
class Derived2 : Derived1{
void override methodImplementation(){
.. do more things ..
}
}
的不同之处在于在BaseClass.templateMethod()什么被调用在第二行是templateMethod ()而不是methodImplementation(),所以它调用它自己,但是从父类的“视角”。现在我越来越想这是不可能的,并且比任何事情都造成更多的困惑。
你应该坚持术语'Derived'和'Base',这很容易混淆你想要做的事情...... – user3292642
this.base可能不是一件东西,而只是基础。templateMethod()应该是? – Slicc
如果您只想从派生类调用基类的方法。为什么你需要使方法抽象并覆盖它? – user3292642