Today, I encountered an interesting problem in the community. How can I use the same processing method for the click event of button1 and the click event of button2 without knowing the method name, I have already answered a similar question, which is implemented using the delegate list class. The Code is as follows:
- Private void form1_load (Object sender, eventargs E)
- {
- Button btn1 = new button ();
- Btn1.text = "button1 ";
- Btn1.click + = new eventhandler (delegate (Object S, eventargs E2) {MessageBox. Show (S. tostring ());});
- Btn1.name = "btn1 ";
- Btn1.location = new point (10, 10 );
- This. Controls. Add (btn1 );
- Button btn2 = new button ();
- Btn2.text = "button2 ";
- Btn2.name = "btn2 ";
- Btn2.location = new point (10, 30 );
- Type T = btn1.gettype ();
- Propertyinfo Pi = T. getproperty ("Events", bindingflags. instance | bindingflags. nonpublic); // obtain the event attribute of button1
- Eventhandlerlist EHL = (eventhandlerlist) PI. getvalue (btn1, null); // obtain the delegate list of button1
- Fieldinfo = (typeof (Control). getfield ("eventclick", bindingflags. Static | bindingflags. nonpublic );
- Delegate d = EHL [fieldinfo. getvalue (null)];
- Btn2.click + = (eventhandler) D;
- This. Controls. Add (btn2 );
- }