In-depth discussion
Small order
I haven't come to update blog for a long time, one is because of the work is relatively busy, the most important thing is to pay my girlfriend :), love her too much. After reviewing the article written in front, it seems that everyone still likes my irrigation style, and today, I will write a lot of questions recently asked - commission and events. And put this document to the brothers and sisters who support me and my dear girlfriend (although you can't understand the code, 嘻嘻). To be honest, the "deep" is absolutely unpleasant, I will tell you about it. If there is any flash on the content, the troubles of brothers and sisters take a few bricks - the younger brother is inhaving to cover the house!
text
One. What is delegate
First to point classical interpretation - From MSDN: A delegate is a type① that references a method② Once a delegate is assigned a method, it behaves exactly like that method③ The delegate method can be used like any other method, with parameters and.. a return value.
I will translate it first: delegate (delegate, also known as "agent") is a data type, which references a method. Once it is a delegate distribution (you can understand "Mount"), its behavior will be consistent with this method (hook the connection to call this method, do not match, I still hang up ... I originally foreigner I will also say that the car is 轱轱: p). The commission can be used as in any way, such as or without parameters, and return values, etc.
I gave an example, demonstrate what is delegate.
/ / ======= Water true ======================================================================================================================= == using System; using System.Collections.Generic; using System.Text; namespace DelegateSample {// mines (class) class Mine {public void Blast (int enemies) {Console.WriteLine ( "Killed {0} Japanese soldier (s ) !!! ", enemies);}} / / The yard (class) class yard {public int enemiesinyard; public mine mineinyard = new mine ();} // rope (delegate) public delegate void pullingString (int enemies); / / Warrior (class) Class Soldier {// A soldier can control three mines (you can try to use arraylist, more cool) public pullingstring [] punlingstrings = new pullingstring [3];} // Main program class program program {static void Main (String [] args) {// three yard Yard Yardofzhang = new Yard (); Yard Yardofwang = new Yard (); Yard Yardofli = new Yard (); // 嘎子 给 地 Soldier Gazi = New Soldier (); Gazi.pullingstrings [0] = ne w PullingString (yardOfZhang.mineInYard.Blast); gazi.pullingStrings [1] = new PullingString (yardOfWang.mineInYard.Blast); gazi.pullingStrings [2] = new PullingString (yardOfLi.mineInYard.Blast); // devils coming! There are five devils in the old family, the old king family, and the old Li Jia ten.
yardOfZhang.enemiesInYard = 3; yardOfWang.enemiesInYard = 5; yardOfLi.enemiesInYard = 10; // child of the tailpiece Gazi gazi.pullingStrings [0] (yardOfZhang.enemiesInYard); gazi.pullingStrings [1] (yardOfWang.enemiesInYard); gazi .pullingstrings [2] (Yardofli.enemiesinyard);}}} I have said a word, see if you can understand:
The entrustment is a mechanism that makes it easy to call other classes from a class (this example is the Soldier class) (this example is MINE class) is simple and clear. Reduces the coupling degree and the complexity of the coupling between classes and classes (you can think of it, do not use the delegate, and write the Blast method that calls Mine directly in the Soldier class, the code will be something ...... Head big bar ).
what? do not understand? It doesn't matter, I explain the above code:
1. This code is written in Visual Studio 2005, you can create a console project, completely override the code above for you to prepare the code for you, press CTRL F5 to execute.
2. Mines: only a Blast method of a public, which requires an INT type parameter. This parameter determines the mine to kill a few devils. To emphasize: Blast is a method in the Mine class, pay attention to its "signature", is a VOID type return value plus an INT type parameter.
3. Class: Each yard buried a watery and allows a certain little devil to come in.
4. Rope delegate: This is the core of this example. The warrior wants to explode landmines, there are two ways, one is to take a root incense - the premise is that the courage is enough, the twist is long enough, run enough fast - it is estimated that the little devil is not dry; the other is Hanging on a fire string (no devils do not hang strings ~~), then then pull ~~ Tongue is coming! Sorry! It is a small devil. Then everyone discovered that the rope looked at the warrior, and the other of the mine's Blast, so, the action of the warrior rope was equivalent to the effect of igniting ignition (IT Behaves Exactly Like That Method 3). In other words: The warrior "delegate" to the rope to do this. So, the rope is an example of "commission".
5. Warrior: One warrior can pull three strings, I am represented by an array. Because delegate is a plus / decrease operation (later "multicast entrust", it will be mentioned), so when the parameter is called (the parameters of this example are inconsistent, it is 3, 5, 10) No need for arrays. To emphasize: This is the method of this warrior to adjust the method in the mortar class - cross-class method call.
6. The first piece of code in the main program has created three yards, which are old, old king, and Lao Li family's yard. The second code is our protagonist Zhang Zizi classmate (with Sun Tingzhi) debut ... Same respectively, each string of the hand is on the mine of each yard. The third code - the devil is coming! The fourth code, the 嘎子 classmate completed the task of the Qingfang by pulling the three strings in his hands. two. Entrusted
After reading this code, maybe you will say: Well, is it simple ...
Yes, it is really simple after you have a commission. However, you can try to achieve the same functionality - fully implement, but the relationship between classes and classes will be stirred together, and it will be suddenly complicated. In order to avoid damaging brain cells, I will not give an example. So maybe everyone will ask: C / C has no entrustment, what should I do? Oh, this question is handsome! C / C is the same function as a method of function pointer and callback function. Therefore, the entrusted can be said to be ".NET version of the function pointer", but if you don't know what is the function pointer, it doesn't matter. You only need to remember that the entrusted is developed by the function pointer in C / C . .
In the subsequent days, I will give a program written by C , using a function pointer implementation.
three. upgrade! Broadcast delegate
If the entrustment is just a .NET version of the function pointer, it is really not much meant - Microsoft is of course not so stupid! In fact, it has a lot of improvements compared to the function of the function, and the most practical is also the coolest thing is that the delegation is "multicast", and the function pointer is "unicast". In other words: The delegation is "a pair", which can be hung on a commissioned a number of functions as the signature; and the function pointer can only "one-to-one", that is, a function pointer can only point to a function. To illustrate this, I have improved the first example - the change is relatively large, and many operations move into the constructor of each class (analog VS2005 is the WinForm program for us). By the way, give everyone a small suggestion: Although I will give the example COPY to execute, I also hope that everyone can do itself to knock on the code, so there will be many unexpected gains.
/ / ======= Water true ======================================================================================================================= == using System; using System.Collections.Generic; using System.Text; namespace DelegateSample {// rope (delegate) public delegate void PullingString (); // mines (class) class Mine {private int enemiesInScope; public PullingString stringOfMine; public Mine (int enemisInYard) {enemiesInScope = enemisInYard; stringOfMine = new PullingString (Blast);} public void Blast () {Console.WriteLine ( "Killed {0} Japanese soldier (s) !!!", enemiesInScope);}} // yard (class) class yard {private int enemiesInYard; public Mine mineInYard; public yard (int enemies) {enemiesInYard = enemies; mineInYard = new Mine (enemiesInYard);}} // warrior (class) class soldier {public PullingString mainString } // Main program class class program {static void main (string [] args {// Three yards, the old family of the old family has five devils, the old king family, the old Li Jia ten Yard Yardofzhang = new Yard (3); Yard Yardofwang = new Yard (1); Yard Yardofli = New Yard (10); // Take the rope on the mine to the rope in the hand, here used multicast Soldier Gazi = New Soldier (); gazi.mainstring = Yardofzhang.mineinyard.StringOfmine; Gazi.MainString = Yardofwang.mineinyard.stringofmine; gazi.mainString = Yardofli.mineinyard.stringofmine;
// 嘎子 拉弦 儿 Gazi.mainString ();}}} OK, I will carefully explain the above code. 1. The rope commissioned in this time is different from the last time - it is no. Because there is no parameters, the form is "unified", which is suitable for multicast commission. But here should remind everyone: "Unification" is not necessarily "no", for example, in the WinForm program, it is used to establish an EventHandler delegate of control events. It is 2 parameters, which are Object type Sender and Eventarg type. E, (with the event handler "having such a parameter), this is also" unified ".
2. Mear: This mine is improved. The biggest feature is that it has already brought a rope (instance of the rope commissioned) and exposed to the user. Also, the Blast () method of the mine is changed to no argument - match the rope commission. The number of killing has become Private and is initialized at the constructor.
3. The number of the yards: there is little change, but the mine example in the yard is initialized at the constructor. Like this method of initializing a member variable in a constructor, it is very common in programming.
4. Warrior: Very big, no longer holding 3 rings, but only one rope. Just connect the rope on the mine to 1 rope in your hand, then pull it ... Oh, the effect of pulling 3 rings is nothing difference.
5. Enter the main program, you will find: Because a lot of action is handed over to the class's constructor, the main program seems to be simple and easy. The first piece of code is to generate three hospitals. The second code is the core of this program - multicast commission - notice that the delegate can use = this operator? = Operator can combine a set of entrusted signs to together (reverse, - = operator removes unwanted delegate), which is the function of function pointer does not have. The last code, pulling 1 rope is equivalent to pulling the rope on 3 mines.
6. Please take a closer look = this code, and feel this: During the process development process, there are two programmers, one is a class library and an infrastructure (one is the use of class libraries. Write a target program. After the class developer has developed the class library, it is generally a person who will be compiled, including the class-containing DLL files to write a target program - in other words, the programmer of the write target program cannot be seen from the source code of the class. It is also impossible to change the source code of the class. Assuming that this mechanism is not entrusted, then each time the interaction between class and classes is added, the class code is changed and compiled once. The solution is that either write class library and write target programs are the same person (such a large program to write), or write the personnel of the class library with the person who writes the target program for extremely frequent communication and version maintenance (BUG It is extremely high) ... and there is a problem that it is impossible to avoid, that is, your program becomes a pot of fried sauce (the coupling relationship between classes and classes is too close, the code twisted together). The existence of the commission, so that the interaction between the class and the class is independent of class code, solves all of the above problems.