The whole framework of 1.c# 's handling events is actually an application of the Observer pattern .
Viewer mode: the teacher monitors The students ' exams, and if the students cheat , the teacher immediately hits
2. The elements involved:
So there must be two objects involved, event initiator (trigger)--student; event handler--Teacher
It also involves two events , triggering events-cheating; handling events-hitting people
3. Student Class
In fact, cheating is a delegate, and the delegate is a set of functions, function Class (Khan!!) The name of the Commission sucks.)
Public event EventHandler cheating;//This event is caused by a student, so the event should be written in the student class
Triggering events
public void testing () {
//...
if (cheating!=null)
Cheating (this,new EventArgs ());//All said, the Commission is the essence of the method, the parameters of the delegate is fixed to two: the first to ask the Trigger object; the second is the parameter EventArgs
}
4. Teacher Class
Student _student = new Student ();//The teacher monitors the students, so the student is written as a member variable of the teacher, combined
_student. Cheating + = new EventHandler (slapstudent);
Handling events is, of course, written by the Watcher (Observer).
public void Slapstudent (Object Sender,eventargs e) {
Give the students a slap
}
C # Custom processing events (the author has not fully understood events and delegates, so it is possible to make mistakes)