C # event triggering mechanism, similar to C + + callback function mechanism
Let me say briefly, the nature of the Commission and the event, and then re-open a blog in detail.
Delegate: A pointer to a method, a function pointer similar to C
Event: is a data structure that can hold 0 or more method pointers .... A class is generated for it after a compilation, and so on, and so on, and then another blog post.
Look at the trigger mechanism.
easy to understand, to a popular figure
Event Trigger Source Class
classCclass {Private Chari; Public Delegate voidichanged (Cclass s); Public Eventichanged value_changed; protected Virtual voidOnValueChanged (Cclass message_str)//triggering an event in the Onxxxxxx method{ichanged temp_value_changed= Volatile.read (refvalue_changed);//Keep thread safe, keep a backup if(Temp_value_changed! =NULL) {temp_value_changed (MESSAGE_STR); } } Public CharI {Get { returni; } Set { if(value!=i) {i=value; This. onvaluechanged ( This);//Call the Onxxxxxxx method when the value is modified } } } }
Registering a method for an event in another class, triggering an event when modifying a value, executing a method
classProgram {Static voidMain (string[] args) {Cclass C=NewCclass (); C.value_changed+=c_value_changed;//Register the method on the event, Chari =Console.readkey (). KeyChar; while(i!= -)//Enter Exit{Console.WriteLine (); C.I.= i;//values are modified, events are triggered, and all methods registered to the event are executedi =Console.readkey (). KeyChar; } } Private Static voidc_value_changed (Cclass s) {Console.WriteLine ("value is changed>>>>i:"+s.i); } }
Effect
Source Connection: Http://pan.baidu.com/s/1i3UXHKp
C # event triggering mechanism