在派生的抽象类中实现事件的实现

Adr*_*and 6 c# events delegates interface abstract

我正在尝试创建我正在考虑的翻译类,以便我的程序可以与各种目标平台对话.每个平台都将由抽象类的单独实现处理.为了简单起见,我减少了一些东西.

我有一个抽象类,有几个抽象方法:

abstract class ControllerBase
{
    public abstract bool EnableDTMFDetection(string CallID, Party Party);
    public abstract bool DisableDTMFDetection(string CallID, Party Party);
}
Run Code Online (Sandbox Code Playgroud)

随后是一个派生自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;
    }
}
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.对于PlatformOne,我被迫定义每个方法,规定如何将传出消息发送到目标平台.

是我的传入事件.我需要能够从派生类中引发事件.当我将以下内容添加到controllerbase时:

    public delegate void MyEventHandler(object sender, EventArgs e);
    public event MyEventHandler MyEvent;
Run Code Online (Sandbox Code Playgroud)

它编译得很好,但我不能在我的派生类中引发事件而没有错误:"事件'ControllerBase.MyEvent'只能出现在+ =或 - =的左侧(除非在输入'ControllerBase')"

那么,a)如何从我的派生类中引发我的事件,以及b)是否有人可以建议一种机制来强制从我的派生类(抽象函数或接口方法)中强制指定事件的连接.谢谢你致电:)

Jon*_*eet 10

最简单的方法是在基类中编写一个方法来提高它:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

可能希望将其设置为虚拟方法,以便可以在派生类中覆盖它...这取决于您的用例.

请注意,这不是强制派生类中任何内容的实现 - 但我认为这是您真正想要的.