標籤: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#中事件的動態調用實現方法