我正在尝试创建我正在考虑的翻译类,以便我的程序可以与各种目标平台对话.每个平台都将由抽象类的单独实现处理.为了简单起见,我减少了一些东西.
我有一个抽象类,有几个抽象方法:
abstract class ControllerBase
{
public abstract bool EnableDTMFDetection(string CallID,Party Party);
public abstract bool disableDTMFDetection(string CallID,Party Party);
}
随后是一个派生自ControllerBase的类(类),并完全实现这些方法:
class PlatformOne : ControllerBase
{
public override bool EnableDTMFDetection(string CallID,Party Party)
{
// Do Stuff
return true;
}
public override bool disableDTMFDetection(string CallID,Party Party)
{
// Do Stuff
return true;
}
}
到现在为止还挺好.对于PlatformOne,我被迫定义每个方法,规定如何将传出消息发送到目标平台.
是我的传入事件.我需要能够从派生类中引发事件.当我将以下内容添加到controllerbase时:
public delegate void MyEventHandler(object sender,EventArgs e);
public event MyEventHandler MyEvent;
它编译得很好,但我不能在我的派生类中引发事件而没有错误:“事件’ControllerBase.MyEvent’只能出现在=或 – =的左侧(除非在类型中使用) ‘ControllerBase’)”
那么,a)如何从我的派生类中引发我的事件,以及b)是否有人可以建议一种机制来强制从我的派生类(抽象函数或接口方法)中强制指定事件的连接.谢谢你致电:)
解决方法
最简单的方法是在基类中编写一个方法来提高它:
protected void OnMyEvent(EventArgs e)
{
// Note the copy to a local variable,so that we don't risk a
// NullReferenceException if another thread unsubscribes between the test and
// the invocation.
EventHandler handler = MyEvent;
if (handler != null)
{
handler(this,e);
}
}
您可能希望将其设置为虚拟方法,以便可以在派生类中覆盖它…这取决于您的用例.
请注意,这不是强制派生类中任何内容的实现 – 但我认为这是您真正想要的.