Delegate (C # programming guide)
A delegate is a type of reference method. Once a method is assigned to the Delegate, the delegate has the same behavior as the delegate. The use of delegate methods can have parameters and return values like any other method, as shown in the following example:
C # copy code
public delegate int PerformCalculation(int x, int y);
Any method that matches the delegate signature (composed of the return type and parameters) can be assigned to the delegate. In this way, you can change the method call by programming and insert new code into the existing class. As long as you know the signature of the Delegate, you can allocate your own delegate method.
The ability to reference methods as parameters makes delegation an ideal choice for defining callback methods. For example, you can pass a reference to the method of comparing two objects to the sorting algorithm. Separating the comparison Code allows you to write algorithms in a more common way.
Delegation Overview
Delegation has the following features:
The delegate is similar to a C ++ function pointer, but it is type-safe.
The delegate allows passing methods as parameters.
A delegate can be used to define a callback method.
The delegate can be linked together. For example, multiple methods can be called for an event.
The method does not need to be exactly matched with the delegate signature. For more information, see covariant and inverter.
C #2.0 introduces the concept of anonymous methods, which allow passing code blocks as parameters instead of Individually Defined methods.
Content of this section
Delegation Overview
When to use delegation instead of using interfaces
Naming Method
Anonymous Method
Coordination and Inverter
How to: Merge delegates
How to: declare, instantiate, and use a delegate
C # Language Specification
For more information, see the following sections in the C # Language Specification:
1.11 Commission
4.2.6 delegate type
7.5.5.2 delegate call
15. Delegate
(Source: msdn)