先写结论:需要委托的地方,直接delegate bool MyDelegate(int m);
然后需要用的地方,设置参数即可。
具体如下解释:
一个取出数组中大于等于10的数的方法如下代码,
static List<int> BiggerThanTen(List<int> list) { List<int> newList = new List<int>(); foreach(var num in list) { if(num>=10) { newList.Add(num); } } return newList; }
显然,若是需要取出偶数、奇数等数组,就要更改方法,为了C#的封装思想,封闭代码,引出了委托。(以下委托将Delegate方法封装了)
class Program { delegate bool Function(int num);//第一步,声明委托 //第三步,传入委托,后面有新需求时候,只需在此处新建即可,无需修改函数 static Function GreatThan10 = delegate (int n) {return n >= 10; }; static Function IsEven = delegate (int n) { return n %2== 0; }; //其中,()中参数应与第一步中参数对应,{}中为代码主体。 static List<int> Delegate(List<int> list, Function function)//第二步,修改形参列表 { List<int> newList = new List<int>(); foreach (var num in list) { if (function(num))//第二步,修改形参列表 { newList.Add(num); } } return newList; }
//第三步,传入委托 Delegate(list, GreatThan10); Delegate(list, IsEven);//IsEven等于delegate (int n) { return n %2== 0; } //现在开始简化,也就是Lambda Delegate(list, delegate (int n) { return n % 2 == 0; }); //用=>替换delegate Delegate(list, (int n)=> { return n % 2 == 0; }); //int在第一步的声明中已经已知,去掉 Delegate(list, ( n) => { return n % 2 == 0; }); //当()中只有一个参数,()去掉 Delegate(list, n => { return n % 2 == 0; }); //{}中只有一条语句的时候,去掉{return ;} Delegate(list, n => n % 2 == 0); //取出偶数 var list2 = Delegate(list, n => n % 2 == 0); //取出奇数 var list3 = Delegate(list, n => n % 2 == 1);
注意哦,委托一般是:自定义了一个方法A(int a),然后在()里加了一个委托A(int a,Fuc fuc),需要绑定到方法中。
委托应用场景:需要传入相同参数,而判断条件不同,这个时候可以考虑引入委托。
Action: list.Foreach(i=>Console.WriteLine(i));
Foreach方法用到了Action委托,无返回值。即遍历list中的每一个元素i,进行委托,进行打印操作.
Func:有返回值
Predicate(谓词,即返回布尔值!!!!):list.Find();