C# 在派生方法之前自动调用基方法
我有一个基本类:C# 在派生方法之前自动调用基方法,c#,inheritance,derived-class,base-class,C#,Inheritance,Derived Class,Base Class,我有一个基本类: abstract class ClassPlugin { public ClassPlugin(eGuiType _guyType) { GuiType = _guyType; } public eGuiType GuiType; protected void Notify(bool b) { ... } protected virtual void RaiseAct
abstract class ClassPlugin
{
public ClassPlugin(eGuiType _guyType)
{
GuiType = _guyType;
}
public eGuiType GuiType;
protected void Notify(bool b)
{
...
}
protected virtual void RaiseAction()
{
Notify(false);
}
}
然后我有一些派生类:
class ClassStartWF : ClassPlugin
{
public ClassStartWF(eGuiType _guyType) : base(_guyType) { }
public event delegate_NoPar OnStartWorkFlow_Ok;
public void Action()
{
Notify(true);
RaiseAction(eEventType.OK);
}
public new void RaiseAction(eEventType eventType)
{
base.RaiseAction();<--------------------
if (OnStartWorkFlow_Ok == null)
MessageBox.Show("Event OnStartWorkFlow_Ok null");
else
OnStartWorkFlow_Ok();
}
}
}
class ClassStartWF:ClassPlugin
{
公共类startwf(eGuiType _guyType):基(_guyType){}
公共事件代表\u NoPar on开始工作流程\u Ok;
公共无效行动()
{
通知(真实);
RaiseAction(eEventType.OK);
}
public new void RaiseAction(eEventType事件类型)
{
base.RaiseAction();标准解决方案是使用模板方法模式:
然后您的派生类只覆盖SomeMethodImpl
。执行SomeMethod
将始终执行“预工作”,然后执行自定义行为,然后执行“后期工作”
(在这种情况下,不清楚您希望Notify
/RaiseEvent
方法如何交互,但您应该能够适当地调整上面的示例。)为什么要使用new
而不是覆盖RaiseAction
?这是一种奇怪的方法。是的,很抱歉没有意识到这一点。Editing@JonSkeet:仔细检查,询问者似乎根本没有重写任何内容。基方法没有参数,而派生方法有。代码似乎一点也不正确。@BoltClock:的确,它我已经回答了问题的全部要点,但忽略了奇怪的样本。
public abstract class Base
{
// Note: this is *not* virtual.
public void SomeMethod()
{
// Do some work here
SomeMethodImpl();
// Do some work here
}
protected abstract void SomeMethodImpl();
}