There are many people asking, delegates in .NET, and event processing. I have a simple example shows that it is an example in reality: For example, a company (scene), you are a boss, there are two employees, Xiaoshu and Xiao Wang. You ordered Xiao Wang, if you play games, then the little king is buckle to 500 yuan. This is the commission in reality. In fact, in the write program, the programmer is the boss, Xiaoshu and Xiao Wang are two objects. Small play game is a method, Xiao Zhang also has a game event, he plays games to stimulate this event. Xiao Wang is an event handling object, he is responsible for deducting small money to 500. Therefore, the commission has the following elements:
1
Excited event object
-
That is Xiao Zhang
2
Treatment object events
-
Xiao Wang
3
Defining delegates, that is, you let Xiao Wang monitor small. If these three elements are satisfied, you have written a complete event. There is an example below: Successful operation in the VS.Net2003 C # console application:
Using
System;
Namespace
Csharpconsole
{Public class scene {[stathread] public static void main (string [] args) {console.writeline ("Scene starts."); // Generate Xiao Wang Xiao W = New Xiao Wang (); // Generate small Lend account small Zhang Z = new small (); // Specify monitor Z.PlayGame = new PlayGameHandler (w. Button money); // Start playing game Z. Play game (); console.writeline ("Scenlight end") Console.readLine ();}} // People responsible for dash money public class king {public king () {console.writeline ("Generated Xiao Wang");} public void deduction (Object Sender, Eventargs E) {Console.WriteLine ("Xiao Wang: Good kid, go to work, dare to play games"); console.writeline ("Xiao Wang: See how much your kid" is "); small sheet f = (small) sender; console. Writeline ("Small Money:" f. Money. Tostring ()); console.Writeline ("Start Deduction"); System.Threading.Thread.Sleep (500); f. Money = f. Money - 500 Console.writeline ("After the deduction. Now Xiao Zhang still:" f. Money. Tostring ());}} // If you play, the event public class small {// first defines an event, This event means "small" in playing games. Public Event PlayGameHandler PlayGame; // Save Small Money Variable PRIVATE INT M_MONEY; PUBLIC Small () {Console.Writeline ("Generate Small."); M_money = 1000; // Constructive function, initialization of small money. } Public int money // This property can operate the little money.