加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在派生的抽象类中强制实现事件

发布时间:2020-12-15 18:01:39 所属栏目:百科 来源:网络整理
导读:我正在尝试创建我正在考虑的翻译类,以便我的程序可以与各种目标平台对话.每个平台都将由抽象类的单独实现处理.为了简单起见,我减少了一些东西. 我有一个抽象类,有几个抽象方法: abstract class ControllerBase{ public abstract bool EnableDTMFDetection(s
我正在尝试创建我正在考虑的翻译类,以便我的程序可以与各种目标平台对话.每个平台都将由抽象类的单独实现处理.为了简单起见,我减少了一些东西.

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

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);
    }
}

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读