Delegation is a very important part in C #. When will it be used? Or how do we understand this concept?
C # The delegate can be regarded as a method reference or a method pointer. The biggest difference between it and the function pointer used in c ++ is that the delegate is type-safe.
The return value and detailed parameter list of the method must be listed during the delegate Declaration. In this way, the type security check can be performed when the method is specified for the delegate.
The delegate statement is as follows:
View Code
1 public delegate int AddNum(int value);
It can be seen that the delegate keyword is delegate. Except for this keyword, the rest is a complete method signature format, including the delegate return type, delegate name, and detailed parameter list required by the delegate.
There are several common methods of delegation
1. specify the method by instantiating the delegate object
View Code
1 public delegate int AddNum (int value );
2
3 public int Add (int value)
4 {
5 System. Console. WriteLine (value );
6 return value + 1;
7}
8
9 // specify a method for the delegate Through instantiation
10 AddNum addNum = new AddNum (Add );
2. Delegate the specified method by directly specifying the Method
View Code
1 public delegate int AddNum (int value );
2
3 public int Add (int value)
4 {
5 System. Console. WriteLine (value );
6 return value + 1;
7}
8
9 // specify a method for the delegate Through instantiation
10 AddNum addHandler = Add;
3. Use an anonymous method to delegate the specified Method
View Code
1 public delegate int AddNum (int value );
2 // specify a method for the delegate using the anonymous method
3 AddNum addNum = delegate (int value) {return value + 1 ;};
Of course, one delegate can also specify multiple methods. When multiple methods are specified in the delegate, the methods specified by the delegate will be called in sequence.
View Code
1 public delegate int AddNum (int value );
2 public int Add (int value)
3 {
4 value + = 1;
5 System. Console. WriteLine (value );
6 return value;
7}
8
9 public int Add2 (int value)
10 {
11 value + = 2;
12 System. Console. WriteLine (value );
13 return value;
14}
15
16 public void Test ()
17 {
18 // specify the Add method for the delegate addHandler
19 AddNum addNum = Add;
20 // Add the Add2 Method to the Delegate
21 addNum + = Add2;
22 addNum (2 );
23}
We can use the + = operation to add the delegate method, and the-= operation to remove the delegate method.
A delegate can substitute a method as a parameter into another method. A delegate can be understood as a reference to a function.