触发事件,检查是否注册过事件的方法
下面的代码,会发现事件没有被注册
class Program { static void Main(string[] args) { EventCheck check = new EventCheck(); check.OnDataArrived(new DataArrivedEventArgs() { data="Hello World!"}); Console.ReadKey(); } static void check_DataArrived(object sender, DataArrivedEventArgs e) { Console.WriteLine(e.data); } } class EventCheck { //第三步 use the delegate type to declare a variable that can refer to any method with the same signature as the delegate. //To associate the event with the method that will handle the event, add an instance of the delegate to the event. //The event handler is called whenever the event occurs, unless you remove the delegate. internal event DataArrivedEventHandler DataArrived; //第四步 internal void OnDataArrived(DataArrivedEventArgs e) { try { //DataArrivedEventHandler handler = DataArrived; //if (handler != null) //{ // handler(this, e); //} DataArrived += EventCheck_DataArrived; if (DataArrived != null) { DataArrived -= EventCheck_DataArrived; DataArrived(this, e); } } catch (Exception ex) { Console.WriteLine("遇到异常{0}", ex.Message); } } void EventCheck_DataArrived(object sender, DataArrivedEventArgs e) { Console.WriteLine(e.data); } } //第二步 Represents the method that will handle an event when the event provides data. //This method's first parameter is of type Object and refers to the instance that raises the event. //Its second parameter is derived from type EventArgs and holds the event data. //If the event does not generate event data, the second parameter is simply the value of the EventArgs.Empty field. //Otherwise, the second parameter is a type derived from EventArgs and supplies any fields or properties needed to hold the event data. delegate void DataArrivedEventHandler(object sender,DataArrivedEventArgs e); //正式写代码的时候,可以使用EventHandler<TEventArgs>泛型委托 //第一步 //create a custom event data class, create a class that derives from the EventArgs class and provide the properties to store the necessary data. //The name of your custom event data class should end with EventArgs. class DataArrivedEventArgs : EventArgs { internal string data; }
修改第四步的代码,先将事件复制到临时变量里面,然后通过这个临时变量来处理,就不会有问题
//第四步 internal void OnDataArrived(DataArrivedEventArgs e) { try { //DataArrivedEventHandler handler = DataArrived; //if (handler != null) //{ // handler(this, e); //} DataArrived += EventCheck_DataArrived; DataArrivedEventHandler handler = DataArrived; if (handler != null) { DataArrived -= EventCheck_DataArrived; handler(this, e); } } catch (Exception ex) { Console.WriteLine("遇到异常{0}", ex.Message); } }
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了