First, the principle of delegation:
In essence, a delegate is a data type that describes a class of methods with the same parameter signature and return value. An instantiated delegate can be thought of as a list of methods with the same parameter signature and return value. Any delegate object is an object of some derived class of System.Delegate.
Second, the definition of delegation:
///Define a delegate delegate int Plus(int x,int y); //Instantiate the delegate in the method public void Test() {
//You can New an instance delegate object, you must specify a function Plus p= new SayHello(Num);
//You can also specify a function directly p += Num;
//The lambda expression is also a function in essence, so it can be written like this p +=(x,y)=>x+y;
When an instantiated delegate specifies multiple methods and all have return values, only the return value of the last method can be received when the delegate is executed int a= p(1,2); } public int Num (int x, int y) { return x + y; }
Three, c# built-in delegate, Action, Func
The c# grammar helps us define two default delegate types, Action and Func. Action delegates can have parameters but no return value. Func has return values and can have parameters.
//Instantiate an Action delegate Action<string> sayHello=x=>{Console.Write(x);}; sayHello("Have you eaten today?"); //Instantiate a Func delegate Func<int, int, int> plus = (x, y) => { return x + y; }; var num = plus (1, 8);
Fourth, the use of delegation
1. Pass it as a parameter in the method
public int Test() {
//Call the method and pass the lambda expression as a parameter
return Operation((x,y)=> { return x + y; },1,8);
}
public int Operation(Func<int,int,int> lam,int a,int b)
{
return lam(a,b);
}