First, what is a delegate
Delegates, like classes, are user-defined types;
A class represents a collection of data and methods, while a delegate holds one or more methods;
Ii. use of Delegates 1. Declaring delegate types
A delegate is a type, and as with a class, a delegate type must be declared before it is used to create the variable and the object of the type;
Attention:
Start with the delegate keyword;
no method body;
2. Create a Delegate object
A delegate is a reference type, so there are references and objects;
Method One: Use an object with the new operator to create an expression
Method Two: An implicit conversion between a shortcut, a method name, and its corresponding delegate type
3. Assigning a value to a delegate
Because the delegate is a reference type, the reference that is contained in the delegate variable is changed by assigning a value. The old delegate object will be reclaimed by the garbage collector
4. Combination of Delegates
Attention:
The delegate is constant, and the delegate object cannot be changed after it is created
5. Adding a method to a delegate
Note: To add the result of a method to a delegate,
In fact, since the delegate type is immutable, all the results of adding 3 methods to the invocation list of the delegate are actually variables that point to a completely new delegate
6. Removing a method from a delegate
Attention:
If there are multiple instances of a method in the invocation list, the-= operator will search from the last list and remove the first instance that matches the method;
Attempts to delete a method that does not exist in the delegate have no effect;
Attempting to delete an empty delegate throws an exception. We can judge whether the invocation list of a delegate is empty by a delegate and a null comparison. If the invocation list is empty, the delegate is null
7. Invoking delegates
You can invoke a delegate just as you call a method
Attention:
Invoking a delegate with a parameter invokes each member of its invocation list with the same parameter value;
If a method appears more than once in the invocation list, it is called once each time the method is encountered in the list when the delegate is called.
7. Calling a delegate with a return value
Analysis
Attention:
The value returned by the last method in the invocation list is the value returned by the delegate invocation;
The return value of all other methods in the invocation list is ignored
8. Calling a delegate with reference parameters
Attention:
If the delegate has a reference parameter, the parameter value changes based on the return value of one or more methods in the invocation list;
When the next method in the delegate list is called, the new value of the parameter is passed to the next method;
C # knowledge points-Delegates