The delegate event mechanism in C # is one of the highlights of this language, in a more secure and efficient way to achieve similar C language function pointers, the signal slot mechanism in QT and the mechanism of the delegation event is quite similar in practical application, but the use of C # is more convenient. Next, I'll put a diagram to show how an event mechanism works:
650) this.width=650; "title=" References other posts "alt=" wkiom1s9v22zuzedaadwsmo5sea502.jpg "src=" http://s3.51cto.com/wyfs02/M00/ 58/d2/wkiom1s9v22zuzedaadwsmo5sea502.jpg "/>
The role of the Publisher class above is to define delegates, define events, and define methods for triggering events;
The role of the Subscriber class registers events and defines specific event handling methods. (As if the Subscriber class does not need to register the event, the registration event is performed in the running module)
This thought I think is: Do not think well how to do the first frame (write a function declaration), after those customers who want to concrete how to do, after his own ways to go, we only put the function signature declaration good enough, lest the customer is not satisfied with our meticulous definition.
"I feel that explaining the event is still a bit difficult to understand, and I think understanding events is actually about connecting events and event handlers by registering events, and when events occur, we register our required event handlers with the event to make our satisfying process happen." 】
For example, use the C # event mechanism as a reference to someone else's blog
using system;using system.collections.generic;using system.text;using system.threading; namespace delegate_and_event{ public delegate void Salarycomputeeventhander (object sender, myeventargs e); public Class employee { public event SalaryComputeEventHander SalaryCompute; public Virtual void onsalarycompute (myeventargs e) //trigger event function { if (SalaryCompute != null) { salarycompute (this,e); } } } public class MyEventArgs : EventArgs { public readonly double _salary; public myeventargs (double salary) { this._salary = salary ; } } public class humanresource { // The specific event handler function public void salaryhandler (object Sender, myeventargs e) { &nbSp Console.Write ("salary is {0}", E._salary); } } class Program { static void main (String[] args) { employee ep = new Employee (); humanresource hr = new humanresource (); MyEventArgs e = new MyEventArgs (20000.5); ep. Salarycompute += new salarycomputeeventhander (HR. Salaryhandler) //Register the event handler function with in the event while (True) { thread.sleep (; ) ep. Onsalarycompute (e); } } } }
Detailed C # event mechanism