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

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

概述我正在尝试创建我正在考虑的翻译类,以便我的程序可以与各种目标平台对话.每个平台都将由抽象类的单独实现处理.为了简单起见,我减少了一些东西. 我有一个抽象类,有几个抽象方法: abstract class ControllerBase{ public abstract bool EnableDTMFDetection(string CallID, Party Party); pub 我正在尝试创建我正在考虑的翻译类,以便我的程序可以与各种目标平台对话.每个平台都将由抽象类的单独实现处理.为了简单起见,我减少了一些东西.

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

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

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

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

总结

以上是内存溢出为你收集整理的c# – 在派生的抽象类中强制实现事件全部内容,希望文章能够帮你解决c# – 在派生的抽象类中强制实现事件所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1238762.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存