namespaceconsoleapplication2{classProgram {Private Static voidStudent_registerfinish () {Console.WriteLine ("Registration Successful"); } Static voidMain (string[] args) { stringStuname =Console.ReadLine (); Student Stu=NewStudent (stuname); //Subscribe to the registerfinish of the student classStu. Registerfinish + =NewStudent.delegateregisterfinisheventhandler (student_registerfinish); Stu. Register ();//Notify event subscribers when an event occurs } } classStudent { Public Delegate voidDelegateregisterfinisheventhandler ();//Defining Delegates Public EventDelegateregisterfinisheventhandler Registerfinish;//defining events through delegates Private stringname; PublicStudent (stringname) { This. Name =name; } Public voidRegister () {Console.WriteLine ("Student {0} to register", name); if(Registerfinish! =NULL) {registerfinish ();//Raising an event } } }}
1. Relationship of events to delegates
An event is a specialized delegate, and a delegate is the basis of an event;
2. Understanding
An event is a message sent by an object that sends a signal informing the customer that an action has occurred. This operation may be caused by a mouse click, or it may be triggered by some other program logic. The sender of an event does not need to know that the object or method receives the event it raises, and the sender only needs to know the intermediary that exists between it and the receiver (deletgate)
3. Defining events
Define a delegate before you define an event
public delegate void Delegateeventhandler ();
Define an event
Private event Delegateeventhandler Eventme;
4. Subscribing to an event refers to adding a delegate that invokes a method when the event is raised. Subscribes an event to an object when the event exists.
Eventme + = new Delegateeventhandler (//method to be referenced); The method for this reference is to subscribe to the event
5. Raising an event means that you want to notify all objects that subscribe to an event and need to raise the event. Raising an event is similar to calling a method.
Eventme (); Raises the event
6. Features
A. An event can subscribe to multiple subscribers.
B. When the publisher determines when an event is raised, the Subscriber determines what action to take in response to the event
C. No subscriber events will never be called
D. Events are typically used to notify actions
4. Event Chapter