[英]How to force inheriting class's method implementation to call base method before invoke own implantation?
I wrote some not sealed class that contain 3 virtual public method and one private method. 我写了一些未密封的类,其中包含3个虚拟公共方法和一个私有方法。
And i make this class public that all my develop group member could use this class ( include inherits and override the virtual public methods ) . 而且我公开了这个类,我的所有开发组成员都可以使用这个类(包括继承和覆盖虚拟公共方法)。
One of the private method name is 'PrivateMethod77()'. 私有方法名称之一是“ PrivateMethod77()”。
Each time the public method 'PublicMethod77()' is call => the 'PrivateMethod77' is call in the first line of the method implementation ( after this line there are more implication logic ). 每次调用公共方法'PublicMethod77()'=>时,在方法实现的第一行中调用'PrivateMethod77'(在此行之后有更多的蕴含逻辑)。
I want to keep this logic and 'force' the inherits and override of the method PublicMethod77 to call the PrivateMethod77 method as the first line of the PublicMethod77 我想保持这种逻辑,并“强制”方法PublicMethod77的继承和重写,以将PrivateMethod77方法作为PublicMethod77的第一行来调用
Is there a way to do it ? 有办法吗?
I don't think that you can enforce the inheriting classes to always first call a method's super implementation, but: 我不认为您可以强制继承类始终始终首先调用方法的超级实现,但是:
Normally I use a Template method pattern for cases like this: 通常,对于以下情况,我使用Template方法模式 :
public abstract class TemplateEnforcer
{
private void TheSame()
{
Console.WriteLine("Everyone calls me;");
}
public void TemplateMethod()
{
this.TheSame();
this.NeedsImplementation();
}
protected abstract void NeedsImplementation();
}
public class TemplateImplementer : TemplateEnforcer
{
protected override void NeedsImplementation()
{
Console.WriteLine("Implemented in TemplateImplementer");
}
}
Code output for this call new TemplateImplementer().TemplateMethod()
: 此调用的代码输出new TemplateImplementer().TemplateMethod()
:
//Everyone calls me;
//Implemented in TemplateImplementer
Template method pattern benefits: 模板方法模式的优点:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.