C # delegation
Trust and events are widely used in. NET Framework [1]. However, it is not easy for many people who have been in contact with C # for a long time to understand delegation and events.
C # demonstrate simple delegate usage
Example: a code that demonstrates the delegate and finally provides the result.
| The code is as follows: |
Copy code |
Using System; Namespace Example. Dele { Class Operations { Public static double MulTwo (double value) { Return value * 2; } Public static double Square (double value) { Return value * value; } } Delegate double DoubleOp (double x ); Class Dele { Static void Main () { DoubleOp [] op = { New DoubleOp (Operations. MulTwo ), New DoubleOp (Operations. Square) }; For (int I = 0; I <op. Length; I ++) { Console. WriteLine ("use Operation No. {0}", I ); Displays (op [I], 1.5 ); Displays (op [I], 3.14 ); Display (op [I], 10 ); Console. WriteLine (); } } Static void Display (DoubleOp action, double value) { Double result = action (value ); Console. WriteLine ("{0} calculation result is {1}", value, result ); } } } |
C # delegate benefits
A person has three sons, asking them to take one thing out and bring back one prey.
It can be understood as a father's commitment to his son:
Prey method (tool)
The methods for entrusting the three members are different.
Rabbit hunting (tool bow)
Buy pheasant (tool money)
Wolf Trap (Tool trap)
A delegate is a type used to indicate all methods in the same form (the return values are of the same type and parameters are the same ).
Public delegate double Handler (double [] ds );
Public double Sum (double [] ds) {// perform the operation in the method .}
Public double Average (double [] ds) {// perform the operation in the method .}
Delegation instantiation
Use the new keyword (using the method name as a parameter) to generate a delegate object and establish the association between the delegate and the method.
Example: Handler handler = new Handler (Sum); you can use a delegate instance like a variable. When using a delegate, you must pass parameters to the delegate as required.
If the delegate is used, the method associated with the delegate is called.
Example: double [] weights = {1.0, 2.0, 3.0, 4.0 };
Double result = handler (weights );
A single delegate can be associated with multiple methods through a + operator delegate, which is called a multi-channel broadcast delegate (corresponding to a single-channel broadcast delegate ).
If a delegate is used at this time, all associated methods are called.
Example: Handler handler = new Handler (Sum );
Handler + = new Handler (Average );
This delegate (a third party) will call the method to help you implement it.
Benefits of delegation:
1. It is equivalent to using the method as another method parameter (similar to the function pointer of C)
2. Serve as a bridge between two methods that cannot be called directly. For example, delegate is required for cross-thread method calls in multiple threads.