Definition of events in C #:
A class or object can notify other classes or objects of a related thing that occurs through an event. The class that sends (or causes) the event is called the publisher, and the class that receives (or processes) The event is called a Subscriber.
Events have the following characteristics:
- The publisher determines when the event is raised, and the subscriber determines what action to take in response to the event.
- An event can have multiple subscribers. One subscriber can handle multiple events from multiple publishers.
- Events that do not have subscribers are never called.
- Events are typically used to notify user actions, such as button clicks or menu selection actions in the graphical user interface.
- If an event has more than one subscriber, multiple event handlers are used at the same pace when the event is raised. To invoke an event asynchronously, see invoke synchronous methods asynchronously.
- Events can be used to synchronize threads.
In the. NET Framework class library, events are based on the eventhandle and EventArgs base classes.
For example, the following code:
delegate void Mydele (String str)//define Delegates
Class Program
{
Event Mydele MyEvent; Defining events
static void Main (string[] args)
{
Program Pro = new Program ();
Subscription method
Pro. MyEvent + = new Mydele (pro. MyMethod);
Pro. MyMethod ("parameters");
}
Defining delegate methods
public void MyMethod (String str)
{
Console.WriteLine ("Method parameter is:" + str);
}
}
Output Result:
The method parameter is: Parameter 1
Summarize:
Key points for using events in C #
1 First, to create a delegate, the format is:
public delegate void delegate name (Object Sender,eventargs e);
Note: A delegate is a function pointer inside C, in which the arguments are fixed because of the event to pass and the object information that triggers the event. The general format of the delegate name is: Name +eventhandle. Such a comparison specification.
2 Then create an event field:
Public event delegate type events name;
Note: The event keyword represents events, and the return type is delegate;
3 Define a method to handle the event
4 finally create a method to trigger the event
When using events, it is common to define two methods, one that is always the same as the delegate signature of the event definition.
The method of binding an event is simple, with + = To add an event,-= to indicate a delete event
Some references from: http://wayfarer.cnblogs.com/archive/2004/04/20/6712.html
C # Events and EventHandler, EventArgs