Luc*_*uca 0 c# inheritance base-class derived-class
我有一个基类:
abstract class ClassPlugin
{
public ClassPlugin(eGuiType _guyType)
{
GuiType = _guyType;
}
public eGuiType GuiType;
protected void Notify(bool b)
{
...
}
protected virtual void RaiseAction()
{
Notify(false);
}
}
Run Code Online (Sandbox Code Playgroud)
然后我有一些派生类:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在在raise动作中我必须在base.RaiseAction()方法之前调用但是可以忘记了.有没有办法在调用派生方法之前自动调用基本方法(并在那里执行某些操作)?
对此的标准解决方案是使用模板方法模式:
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();
}
Run Code Online (Sandbox Code Playgroud)
然后你的派生类就会覆盖SomeMethodImpl.执行SomeMethod将始终执行"预先工作",然后执行自定义行为,然后执行"后期工作".
(在这种情况下,您不清楚希望Notify/ 您的RaiseEvent方法如何进行交互,但您应该能够适当地调整上面的示例.)