[. Net Object-Oriented Programming Basics] (21) Delegate,. net Object-Oriented Programming
[. Net Object-Oriented Programming Basics] (20) Delegate
In the previous section, I talked about delegation in the anonymous method of LINQ, but it is relatively simple. It doesn't matter if you don't know it clearly. In this section, I will describe delegation in detail.
1. What is delegation?
I want to talk about the study delegation. If I have learned it, I feel that it is simple and cannot be simple. If I have never learned it or want to know it, I think it is very easy. Delegation is very important in. net Object-Oriented Programming and learning design patterns. It is essential to learn and master. net Object-Oriented Programming.
In terms of delegation, it is to hand over some things to others for help. In C #, we can also understand that delegation is a dynamic call method. In this case, it is easy to understand.
We usually need to deal with such an example. For example, there is a Zoo (Zoo) (For me, let's talk about the previous animals) with dogs and Chicken) sheep )......, Some new varieties may come in. If the visitor wants to hear the call of an animal, the administrator can help (the animal only understands the call of the Administrator). This is an example of delegation.
Before implementing delegation, Let's first look at the definition of delegation:
A delegate is a class that defines the type of a method so that the method can be passed as a parameter of another method.In this way, the method is dynamically assigned to parameters, which can avoid the extensive use of If-Else (Switch) statements in the program, and make the program more scalable.
In some books, a delegate or representative means a single thing. To avoid the confusion of another concept Proxy, it is better to call a delegate.
Those who have learned c ++ are very familiar with pointers, and C # does not have pointers,The delegate is used. The difference is that the delegate is a secure type and also object-oriented.
2. Use of delegation
The syntax of the delegate statement is as follows:
Public delegate void Del (string parameter );
Definition delegation basically defines a new class. Therefore, you can define delegation wherever a class is defined, either internally or externally, you can also define the delegate as a top-level object in the namespace. According to the defined visibility, you can add general access modifiers: public, private, and protected on the delegate definition:
In fact, "defining a delegate" refers to "defining a new class ". Only the class is changed to delegate. The Delegate is implemented as a class derived from the base class System. Multicast Delegate, and System. MulticastDelegate is also derived from the base class System. delegate.
Below we use delegation to implement the above zoo instance, the implementation is as follows:
1 /// <summary> 2 // animal class 3 /// </summary> 4 class Zoo 5 {6 public class Manage 7 {8 public delegate void Shout (); 9 public static void CallAnimalShout (Shout shout) 10 {11 shout (); 12} 13} 14 public class Dog15 {16 string name; 17 public Dog (string name) 18 {19 this. name = name; 20} 21 public void DogShout () {22 23 Console. writeLine ("I'm a puppy:" + this. name + "Wang ~ Wang ~ Wang "); 24} 25} 26 public class Sheep27 {28 string name; 29 public Sheep (string name) 30 {31 this. name = name; 32} 33 public void SheepShout () 34 {35 Console. writeLine ("I'm a lamb:" + this. name + "~ Bu ~ Ya "); 36} 37} 38 public class Checken39 {40 string name; 41 public Checken (string name) 42 {43 this. name = name; 44} 45 public void ChickenShout () 46 {47 Console. writeLine ("I'm a chicken:" + this. name + "Oh ~ Woo ~ Oh "); 48} 49} 50}
In addition to various animals, the zoo also has an animal administrator who has a commission. The call is as follows:
// The visitor entrusts the Administrator to call an Animal Zoo. dog dog = new Zoo. dog ("Wang Cai"); Zoo. manage. shout shout = new Zoo. manage. shout (dog. dogShout); // The Administrator receives the delegate and sends it to the animal. The animal executes the owner's command Zoo. manage. callAnimalShout (shout );
The running result is as follows:
The above instance implements the definition and call of the Delegate, that is, indirectly calling the methods called by animals. Some may say, why don't we directly call the method called by a dog, instead of using delegation around a large circle. If you just want an animal to be called, it is really a big loop to use delegation, but if I want the dog to finish, let the goat call, and then let the chicken call, I repeatedly asked for the call of several animals. At last, if I had to pay the fee, who would know how much I had consumed? If several animals are called at a time, do we need to write another method called by multiple animals to call them? The role of delegation is embodied in complex calls. Let's take a look at how multiple animals can be called at the same time, that is, the multicast delegation mentioned below.
The delegate must meet four conditions:
A. Declare a delegate type
B. Find a method with the same signature as the delegate type (either instance method or static method)
C. Create a delegate instance using the same signature method
C. Call a method through a delegate instance
3. multicast Delegation
Each delegate only contains one method call. The number of calls to the delegate is the same as the number of calls to the method. If you call multiple methods, you need to call the delegate multiple times. Of course, a delegate can also contain multiple methods. This delegate is called a multicast delegate.
When a multicast delegate is called, it continuously calls each method. In the call process, the delegate must be of the same type, and the return type is generally void. Only in this way can a single instance of the delegate be merged into a multicast delegate. If the delegate has return values and/or output parameters, it returns the return values and parameters of the last called method.
Let's take a look at the implementation that calls "Dog, chicken, and goat:
// Declare the delegate type Zoo. manage. shout shout; // Add shout = new Zoo. manage. shout (new Zoo. dog ("xiaoha "). dogShout); // Add shout + = new Zoo. manage. shout (new Zoo. checken ("Dapeng "). chickenShout); // Add the sheep to authorize shout + = new Zoo. manage. shout (new Zoo. sheep ("Sanlu "). sheepShout); // execute the delegate Zoo. manage. callAnimalShout (shout); Console. readLine ();
The running result is as follows:
The above example,The multicast delegate is added with + =. You can also use-= to remove the delegate..
In the above example, we do not feel enough to reflect the role of delegation. Apart from calling fake animals, we also have other special effects. A dog performs PickUp, A PlayBall, and a chicken Dance)
The audience wanted to watch a group performance, and asked the dog to scream once and grab something back. The goat asked to play the ball once and the chicken to dance once. Then, the order is reversed and the performance is performed again. If you use the direct call method, it is crazy to write the code. If you execute the code one time in sequence, write a row of method code in sequence. If you want to perform the code in turn, write a row of methods in reverse order. This is not a difficult performance. What if it is to be interspersed? Using the object-oriented features of delegation, we can easily implement these requirements. Check the Code:
First, let's improve the way sheep, dogs, and chickens give them a stunt.
1 /// <summary> 2 // animal class 3 /// </summary> 4 class Zoo 5 {6 public class Manage 7 {8 public delegate void del (); 9 10 /// <summary> 11 // animal performances 12 /// </summary> 13 /// <param name = "obj"> </param> 14/ // <param name = "shout"> </param> 15 public static void CallAnimal (del d) 16 {17 d (); 18} 19} 20 public class Dog21 {22 string name; 23 public Dog (string name) 24 {25 this. name = name; 26} 27 public void dosh- Out () 28 {29 Console. WriteLine ("I Am a puppy:" + this. name + "Wang ~ Wang ~ Wang "); 30} 31 public void PickUp () 32 {33 Console. writeLine ("puppy" + this. name + ""); 34} 35} 36 public class Sheep37 {38 string name; 39 public Sheep (string name) 40 {41 this. name = name; 42} 43 public void SheepShout () 44 {45 Console. writeLine ("I'm a lamb:" + this. name + "~ Bu ~ Ya "); 46} 47 public void PlayBall () 48 {49 Console. writeLine ("goat" + this. name + ""); 50} 51} 52 53 public class Chicken54 {55 string name; 56 public Chicken (string name) 57 {58 this. name = name; 59} 60 public void ChickenShout () 61 {62 Console. writeLine ("I'm a chicken:" + this. name + "Oh ~ Woo ~ Woo "); 63} 64 public void Dance () 65 {66 Console. WriteLine (" chicken "+ this. name +" Dance finished "); 67} 68} 69}
The call is as follows:
1 // multicast commission (2) Animal carnival 2 3 // select three animals for the performances 4 Zoo. dog dog = new Zoo. dog ("xiaoha"); 5 Zoo. chicken chicken = new Zoo. chicken ("Dapeng"); 6 Zoo. sheep sheep = new Zoo. sheep ("Sanlu"); 7 8 // Add the dog name to delegate 9 Zoo. manage. del dogShout = dog. dogShout; 10 // Add a chicken call to delegate 11 Zoo. manage. del chickenShout = chicken. chickenShout; 12 // Add the sheep to authorize 13 Zoo. manage. del sheepnShout = sheep. sheepShout; 14 15 // Add the dog to perform 16 Zoo. manage. del dogShow = new Zoo. manage. del (dog. pickUp); 17 // Add a chicken show for 18 Zoo. manage. del chickenShow = new Zoo. manage. del (chicken. dance); 19 // Add the 20 Zoo to the goat performance. manage. del sheepShow = new Zoo. manage. del (sheep. playBall); 21 22 23 // construct the performance mode 24 // The first way of performing: The dog calls one to get one thing back, and the goat calls one to play one; the chicken name is 1 dance and 25 Zoo. manage. del = dogShout + dogShow + chickenShout + chickenShow + sheepnShout + sheepShow; 26 // run the delegate 27 Zoo. manage. callAnimal (del); 28 29 30 Console. writeLine ("\ n Second performance, reverse order \ n"); 31 // Second performance, Reverse Order 32 var del2 = del. getInvocationList (). reverse (); 33 // execute the delegate 34 foreach (Zoo. manage. del d in del2) 35 Zoo. manage. callAnimal (d); 36 Console. readLine ();
The running result is as follows:
<Continue tomorrow .... Unfinished>
========================================================== ========================================================== ====================
Returned directory
<If it is helpful to you, remember to click on the recommendations. If you do not understand the content or do not write it correctly, please contact us more>
QQ: 467189533
========================================================== ========================================================== ====================