Dynamic invocation of events in C implements methods

  • 2020-10-23 20:15:45
  • OfStack

This article gives an example of how C# invokes an event dynamically. Generally speaking, the traditional way of thinking is to get the information of the event through ES2en.EventInfo, then use GetRaiseMethod method to get the method called after the event is triggered, and then use ES5en.Invoke to call to realize the dynamic invocation of the event.

Unfortunately, the Reflection.EventInfo.GetRaiseMethod method always returns null. This is because the C# compiler does not generate metadata information about RaiseMethod at all when compiling and executing events defined by the event keyword, so GetRaiseMethod does not have access to the processing method after the event is triggered. Thottam ES18en. Sriram briefly describes this problem in its Using SetRaiseMethod and and the method dynamically 1, manually generating RaiseMethod using Reflection. Emit related methods, and finally using regular GetRaiseMethod to implement method calls after events are triggered. It's a little more complicated.

The following code is a simple alternative that also implements dynamic invocation of events. The specific code is as follows:


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");

Hopefully this article has helped you with your C# programming


Related articles: