Handling delegates through reflection

Source: Internet
Author: User

The first thing to determine is which event or delegate is processed (this is the usual Click event)

FieldInfo FieldInfo = (typeof (Control)). GetField ("Eventclick", BindingFlags.Static | BindingFlags.NonPublic);

Then get the list of events (buttons used here)

EventHandlerList buttonevents = (eventhandlerlist) this.button1.GetType (). InvokeMember ("Events", System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic, NULL, this.button1, NULL);

It might be easier to read two lines apart.

PropertyInfo PropertyInfo = (typeof (System.Windows.Forms.Button)). GetProperty ("Events", BindingFlags.Instance | BindingFlags.NonPublic); EventHandlerList EventHandlerList = (eventhandlerlist) propertyinfo.getvalue (button1, NULL);

You can get the required property information from the object by reflection. This is the information that gets the event from the button control, the key value in the event's property list is "Events", and then the eventhandlerlist object is disassembled.

Then get all the delegates from the event list that belong to the type of event we're dealing with.

The key value that gets the Eventclick event represents object Eventkey = Fieldinfo.getvalue (null);//Get all events delegate d = Eventhandlerlist[eventkey];

Here's what you can do with loops.

if (d! = null) {foreach (Delegate temp in d.getinvocationlist ()) {Console.WriteLine (temp.  Method.name); This place can clear all the delegates, you can also use the condition to clear the specified delegate, there is no way to directly clear all richtextbox1.appendtext (temp.  Method.name + "\ n"); Cleanup Delegate Eventhandlerlist.removehandler (Eventkey, temp); }}

Codedemo

Handling delegates through reflection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.