The example in this article describes how C # dynamically invokes events. In general, the traditional idea is to obtain information about the event through Reflection.eventinfo, then use the Getraisemethod method to get the method called after the event is triggered, and then use Methodinfo.invoke to invoke the event's dynamic invocation.
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 processing the events defined by the event keyword, so getraisemethod cannot get the event-triggered processing at all. Thottam R. Sriram briefly introduces this issue in its using Setraisemethod and Getraisemethod and invoking the method dynamically, and through reflection . Emit related methods to generate Raisemethod manually, and finally use regular Getraisemethod to implement event-triggered method calls. This is a very complicated practice.
The following code is a simple workaround that also enables 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");
I hope this article is helpful to everyone's C # program design
In addition to the Declaration,
Running GuestArticles are original, reproduced please link to the form of the address of this article
Dynamic invocation implementation method for events in C #
This address: http://www.paobuke.com/develop/c-develop/pbk23546.html
Related content Ò???? édˉ′???? Ó??? ¢μ???????? ¢?òmessageboxexc# to insert a picture in a ListView instance code C # example using the radix sort algorithm to sort strings in C # How to use formal expressions to get the data you want to match
C # access to SQL Server database implementation Method C # Implementation of calling DOS command action class example C # Implementation of the Chinese calendar method on C # object-oriented comprehension
Dynamic invocation implementation method for events in C #