After defining a delegate, we can call back a method like mydelegate (3, 7). In fact, every delegate object is a class object, each delegate object has a synchronous member method of invoke (which is known by msdn). The system actually calls mydelegate. invoke (3, 7 ). what is the internal structure of invoke? Of course, it cannot be found on msdn. I have thought about it and can imitate it!
Internal Implementation of invoke (pseudo code)
1 Sealed Class Mydelegate: multicastdelegate // The class generated by the compiler for us
2 {
3 Public Int Invoke ( Int X, Int Y)
4 {
5 Int Result = 0 ;
6 Delegate [] delegates = This . Getinvocationlist (); // Obtain the delegate list (for more information, see msdn)
7 Foreach (Delegate DELE In Deledates)
8 {
9 Result = Dele. method. Invoke (DELE. Target, New Object [] {X, y }); // Method and target are members of the delegate type, indicating the principal method and the object to which the method belongs. For details, refer to the msdn
10 }
11 Return Result; // Returns the last return value in the delegate chain.
12 }
13 .................................... // Other members
14 }
Getinvocationlist returns an array of the delegate type. The method is a system. reflection. methodinfo type variable, and the target is an object. For details, refer to msdn.