本文實例講述了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#程序設計有所幫助
新聞熱點
疑難解答