Learning c # will be amazed at its delegate. In fact, delegate is not much mysterious. In terms of popularity, delegate is a typed function pointer, which is mainly used for callback.
C ++ is familiar with function pointers. It is a variable that stores the function address, but it does not contain any additional information except the address, such as the number of parameters, parameter type, and return address of the function, function pointers are non-type safe. Delegate provides type security for callback, so that we can write code in a more elegant object-oriented manner when dealing with callback and other issues, in addition, the CLR provides many support for delegate operations (such as the delegate linked list), which simplifies common operations.
When using delegate, you must first define a delegate type, for example:
Public delegate void SomeFunction (Object a, int I ,...);
Note: It is a class definition that can be placed anywhere. This type defines the style of the function received by the delegate: Return void, parameter list...
Then, to use it, you need to define an instance of the SomeFunction class:
Public SomeFunction instance;
Then, we can place "compliant" functions (such as Instance functions and static functions) in the delegate instance ).
Instance + = new SomeFunction (someObject. SomeMethod );
SomeObject is an instance of a certain type. SomeMethod complies with the requirements of this delegate. Otherwise, an error will be reported during compilation.
Finally, you can call the instance directly to implement SomeMethod callback for someObject.
Instance (...);
##########################
The preceding implementation does not seem to show the true value of delegate. But in fact, delegate adds support for the chain. We can apply it as follows:
Instance + = new SomeFunction (someObject. SomeMethod );
Instance + = new SomeFunction (anotherObject. anotherMethod );
...
Then, call instance (...) to activate all the callback functions registered from them.
First, we need to study the internal structure of delegate. Each delegate contains three fields:
Target -- pointing to the object instance to which the callback function belongs (for instance methods)
Method -- points to the callback function
Prev -- pointing to another delegate instance
With prev, you can easily implement the chain support of delegate.
CLR defines the Delegate. Combine and Delegate. Remove static methods to perform operations on the linked list.