C # Custom processing events (the author has not fully understood events and delegates, so it is possible to make mistakes)

Source: Internet
Author: User

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)

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.