1. 程式人生 > >C#中事件的動態調用實現方法

C#中事件的動態調用實現方法

ear too new std 實現 bject multicast using pad

本文實例講述了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來實現事件觸發後的方法調用。這種做法比較繁雜。

以下代碼是一個簡單的替代方案,同樣可以實現事件的動態調用。具體代碼如下:

public event EventHandler<EventArgs> MyEventToBeFired;
public void FireEvent(Guid instanceId, string handler)
{
  // Note: this is being fired from a method with in the same class that defined the event (i.e. "this").
  EventArgs e = new EventArgs(instanceId);
  MulticastDelegate eventDelagate = (MulticastDelegate)this
   .GetType()
   .GetField(handler, BindingFlags.Instance | BindingFlags.NonPublic)
   .GetValue(this);
  Delegate[] delegates = eventDelagate.GetInvocationList();
  foreach (Delegate dlg in delegates)
  {
    dlg.Method.Invoke( dlg.Target, new object[] { this, e } );
  }
}
FireEvent(new Guid(), "MyEventToBeFired");

希望本文所述對大家的C#程序設計有所幫助

除聲明外,跑步客文章均為原創,轉載請以鏈接形式標明本文地址
C#中事件的動態調用實現方法

本文地址: http://www.paobuke.com/develop/c-develop/pbk23546.html






相關內容

技術分享圖片ò????éDˉ′????ó???¢μ????????¢?òMessageBoxEx技術分享圖片C#實現在listview中插入圖片實例代碼技術分享圖片C#中使用基數排序算法對字符串進行排序的示例技術分享圖片在C#中如何使用正式表達式獲取匹配所需數據
技術分享圖片C#訪問SQL Server數據庫的實現方法技術分享圖片C#實現的調用DOS命令操作類實例技術分享圖片C#實現農歷日歷的方法技術分享圖片淺談對c# 面向對象的理解

C#中事件的動態調用實現方法