Delegate Keyword: delegate
A delegate is a method that passes as a parameter.
Declare a delegate first: two parameters, return bool type
Delegate BOOL MyDelegate (object obj1,object obj2);
The method that the delegate corresponds to:
Static BOOL Comparenums (object obj1,object obj2) { return (int) obj1 > ( int ) obj2; }
method to get the maximum value:
Static Object Getmax (object[] objs,mydelegate mydelegate) { object max = objs[0]; foreach (var in objs) { if (comparenums (item, max)) { = item; } } return max; }
Call Method:
Static void Main (string[] args) { object[] nums = {1,2,3, 4,5,0 }; New mydelegate (comparenums); object max = Getmax (nums, Mydel); Console.WriteLine (max); Console.readkey (); }
======== because the method to get the maximum value is used only once, you can use the anonymous method instead, which is more concise =======
Static voidMain (string[] args) { Object[] Nums = {1,2,3,4,5,0 }; MyDelegate Mydel=Delegate(ObjectObj1,ObjectOBJ2) {return(int) Obj1 > (int) Obj2; }; ObjectMax =Getmax (Nums, Mydel); Console.WriteLine (max); Console.readkey (); }
================= because the system comes with action and func two kinds of delegates, there is no need to customize the delegate =================
Action delegate return value is void
Func has a return value
The Get maximum value method is modified to:
Static ObjectGetmax (Object[] objs,func<Object,Object,BOOL>func) { Objectmax = objs[0]; foreach(varIteminchObjs) { if(Comparenums (item, max)) {Max=item; } } returnMax; }
Method calls are modified to:
Static voidMain (string[] args) { Object[] Nums = {1,2,3,4,5,0 }; Func<Object,Object,BOOL> func=Delegate(ObjectObj1,ObjectOBJ2) {return(int) Obj1 > (int) Obj2; }; ObjectMax =Getmax (Nums, func); Console.WriteLine (max); Console.readkey (); }
================= using lambda for simplified ====================
Static voidMain (string[] args) { Object[] Nums = {1,2,3,4,5,0 }; Func<Object,Object,BOOL> func = (obj1, obj2) = {return(int) Obj1 > (int) Obj2; }; ObjectMax =Getmax (Nums, func); Console.WriteLine (max); Console.readkey (); }
C # delegate, anonymous function, lambda evolution