Understanding and understanding of events
A class or object can notify other classes or objects of related events through events.
The publisher determines when an event is triggered, and the user determines the operation to be performed to respond to the event.
In C #, event processing is actually a kind of delegate with special signatures.
Assume that the student receives the score immediately after the instructor registers the score.
The code that the publisher must first write
1. Define a delegate and event and write a method. When this method is called, The Event Notification subscriber is triggered.
Public class Teacher {public delegate void TellScoreEventHandler (object sender, ScoreEventArgs e); public event TellScoreEventHandler tellScoreEvent; /// <summary> // notify the subscriber of an event // </summary> /// <param name = "e"> </param> public void OnTellScore (ScoreEventArgs e) {if (tellScoreEvent! = Null) tellScoreEvent (this, e) ;}/// <summary> // when calling a method, trigger event /// </summary> /// <param name = "name"> </param> /// <param name = "score"> </param> public void tellstudentsocret (string name, int score) {ScoreEventArgs scoreArgs = new ScoreEventArgs (name, score); OnTellScore (scoreArgs );}} /// <summary> /// class of Custom Event Data /// </summary> public class ScoreEventArgs: EventArgs {public int Score {get; set ;} public string Name {get; set;} public ScoreEventArgs (string name, int score) {this. name = name; this. score = score ;}}
2. Add a subscriber first, and then call the method in which the event can be triggered by the publisher.
Student stu = new Student (); Teacher teacher = new Teacher (); teacher. tellScoreEvent + = new Teacher. tellScoreEventHandler (stu. teacher_tellScoreEvent); teacher. tellstudentsocres ("QB struggling", 100 );
3. How to handle an event in a subscriber?
Public class Student {// how to handle the public void teacher_tellScoreEvent (object sender, ScoreEventArgs e) {MessageBox. show (e. name + "tested" + e. score. toString ());}}