Using Reflection allows two events to use the same processing method without knowing the method name.

Source: Internet
Author: User
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:
  1. Private void form1_load (Object sender, eventargs E)
  2. {
  3. Button btn1 = new button ();
  4. Btn1.text = "button1 ";
  5. Btn1.click + = new eventhandler (delegate (Object S, eventargs E2) {MessageBox. Show (S. tostring ());});
  6. Btn1.name = "btn1 ";
  7. Btn1.location = new point (10, 10 );
  8. This. Controls. Add (btn1 );
  9. Button btn2 = new button ();
  10. Btn2.text = "button2 ";
  11. Btn2.name = "btn2 ";
  12. Btn2.location = new point (10, 30 );
  13. Type T = btn1.gettype ();
  14. Propertyinfo Pi = T. getproperty ("Events", bindingflags. instance | bindingflags. nonpublic); // obtain the event attribute of button1
  15. Eventhandlerlist EHL = (eventhandlerlist) PI. getvalue (btn1, null); // obtain the delegate list of button1
  16. Fieldinfo = (typeof (Control). getfield ("eventclick", bindingflags. Static | bindingflags. nonpublic );
  17. Delegate d = EHL [fieldinfo. getvalue (null)];
  18. Btn2.click + = (eventhandler) D;
  19. This. Controls. Add (btn2 );
  20. }

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.