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

來源:互聯網
上載者:User

標籤:sql   命令操作   note   oca   tar   margin   des   代碼   執行個體   

本文執行個體講述了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ˉ′????ó???¢μ????????¢?òMessageBoxExC#實現在listview中插入圖片執行個體代碼C#中使用基數排序演算法對字串進行排序的樣本在C#中如何使用正式運算式擷取匹配所需資料
C#訪問SQL Server資料庫的實現方法C#實現的調用DOS命令操作類執行個體C#實現農曆日曆的方法淺談對c# 物件導向的理解

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.