亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

C#中事件的動態調用

標簽:
C#

    今天遇到一个问题,就是希望能够动态调用事件。传统的思路是,通过Reflection.EventInfo获得事件的信息,然后使用GetRaiseMethod方法获得事件被触发后调用的方法,再使用MethodInfo.Invoke来调用以实现事件的动态调用。

    很不幸,Reflection.EventInfo.GetRaiseMethod方法始终返回null。这是因为,C#编译器在编译并处理由event关键字定义的事件时,根本不会去产生有关RaiseMethod的元数据信息,因此GetRaiseMethod根本无法获得事件触发后的处理方法。Thottam R. Sriram 在其Using SetRaiseMethod and GetRaiseMethod and invoking the method dynamically 一文中简要介绍了这个问题,并通过Reflection.Emit相关的方法来手动生成RaiseMethod,最后使用常规的GetRaiseMethod来实现事件触发后的方法调用。这种做法比较繁杂。以下代码是一个简单的替代方案,同样可以实现事件的动态调用:

view plaincopy to clipboardprint?

  1. public event EventHandler<EventArgs> MyEventToBeFired;   

  2. public void FireEvent(Guid instanceId, string handler)       

  3. {         

  4.     // Note: this is being fired from a method with in the same class that defined the event (i.e. "this").           

  5.     EventArgs e = new EventArgs(instanceId);   

  6.     MulticastDelegate eventDelagate = (MulticastDelegate)this  

  7.       .GetType()   

  8.       .GetField(handler, BindingFlags.Instance | BindingFlags.NonPublic)

  9.       .GetValue(this);   

  10.     Delegate[] delegates = eventDelagate.GetInvocationList();   

  11.     foreach (Delegate dlg in delegates)   

  12.     {   

  13.         dlg.Method.Invoke( dlg.Target, new object[] { this, e } );   

  14.     }   

  15. }   

  16. FireEvent(new Guid(), "MyEventToBeFired");   

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消