1. Delegate
In. in. net, the delegate is a bit similar to the function pointer in C/C ++, but unlike the pointer, the delegate is a safe type, let's take the difference between two numbers as an example to declare a member method first:
Public int comparetwovalue (int A, int B) {int c = A-B; return C ;}
Declare another delegate:
Public Delegate int delemethod (int A, int B );
Then, we can call the member method above through this delegate. Note that the parameter type and return type of the method must match the parameter type and return type of the delegate. In this example, both the member method and delegate input two int values and output an int value.
Public int show () {delemethod d1 = new delemethod (comparetwovalue); // first instantiate return D1 (5, 10); // then call}
2. Anonymous Delegation
This is also called the anonymous method. In fact, this is only a change in the syntax form. Because type matching is still required during compilation, for the show method above, I can use anonymous delegation to express
Public int show1 () {delemethod D2 = delegate (int A, int B) {int c = A-B; return C ;}; return D2 (5, 10 );}
It can be seen that the syntax is simple, so I personally think that anonymous delegation is of no substantial use in C #2.0, because it is truly useful when Lamda expressions are involved in 3.0.
3. Lambda expressions
Use the Lamda expression to write the following method:
Public int show2 () {func <int, Int, int> F = (a, B) =>{ return a-B ;}; return F (5, 10 );}
Lamda expressions are only a manifestation of anonymous delegation. We can intuitively see that the Lamda expression has the least amount of code in the three methods.
Delegate, anonymous delegate, and lambda expressions