C # procedure for customizing events

Source: Internet
Author: User

Generally, C # custom events take the following steps:

1. Declare a delegate: (defines the event type)

For example:

 
  
  
  1. Public Delegate void event name eventhandler (Object serder, eventargs E );

// The event name should be replaced by your own name, and the subsequent eventhandler is the recommended naming convention for C #. Of course, if you do not want to comply with it, you can use any character or even do not want.

If you want to customize the event parameter eventargs, You can derive your own event parameter class from this class, and then replace eventargs with your parameter class in the delegate declaration.

Note: To fully understand the principles of custom events, you need to learn about delegate.

2. Declare an event in your class and use the delegate in step 1 as the event type:

 
  
  
  1. Public event name eventhandler event name;

3. Add the event trigger method in your class.Code:

 
  
  
  1. Event name (this, new eventargs ());

Or:

  
  
  1. If (event name! = NULL)
  2. Event name (this, new eventargs ());

// If you use your own event parameter class, you can replace new eventargs () with your parameter class instance, and save the data you need to pass in your parameter class.

4. C # custom event registration:

Event registration is no different from normal event registration, that is, if an external object needs to respond when your event is triggered, then you can register the event in an external Constructor (or an appropriate location ).

 
  
  
  1. Class instance with event. event name + = new event name eventhandler (event processing method name );

5. Compile the event handling method:

 
  
  
  1. Public void event processing method name (Object sender, eventargs E)
  2. {
  3. // Add your code
  4. }

Note: If you handle your own trigger events in the class, you can select C # Custom Event step 4 and step 5, that is, register yourself, you can also directly call the event processing method in the trigger event code.

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.