@laofang
2016-07-10T04:11:34.000000Z
字数 2530
阅读 1042
.Net
概念: 为了减少重复代码或者增强代码灵活性(下面的两个比较方法可以看出来)可以将方法作为函数传递给一个方法. 用一种数据类型来表示这种可以作为参数的方法, 这种数据叫做委托.
声明: 使用deletage关键字, 后面跟着想是方法声明的东西, 这个方法的签名是委托所引用的方法的签名, 正常方法声明中的方法名称的位置要替换成委托类型的名称.
public delegate bool ComparisonHandler(int first, int second
签名匹配的方法
using System;namespace Console_Test{public class Program {public enum sortType{Greterthan,Lessthan}public static void BubbleSort(int []items, sortType sortType){if (items == null) return;for(int i=items.Length-1; i>=0; i--){for(int j=1; j<= i; j++){bool swap = false;switch (sortType)//比较方法, 代码僵硬不易扩展{case sortType.Greterthan:swap = items[j - 1] > items[j];break;case sortType.Lessthan:swap = items[j - 1] < items[j]; break;}if (swap){int temp = items[j - 1];items[j - 1] = items[j];items[j] = temp;}}}}static void Main(string[] args){int[] items = { 1, 2, 4, 3, 3, 13, 34, 1, 45, 9 };BubbleSort(items, sortType.Greterthan);for(int i=0; i<items.Length; i++){Console.Write(items[i]+" ");}Console.WriteLine();BubbleSort(items, sortType.Lessthan);for (int i = 0; i < items.Length; i++){Console.Write(items[i] + " ");}}}}
using System;namespace Console_Test{//声明委托public delegate bool ComparisonHander(int first, int second);class Program{//声明一个方法(匹配委托签名)//升序public static bool Graterthan(int first, int second){return first > second;}//降序public static bool Lessthan(int first, int second){return first < second;}//冒泡排序public static void BubbleSort(int[] items, ComparisonHander comparisonMethod){int i;int j;int temp;if (comparisonMethod == null){throw new ArgumentNullException("comparisonMethod");}if (items == null){return;}for (i = items.Length - 1; i >= 0; i--){for (j = 1; j <= i; j++){if (comparisonMethod(items[j - 1], items[j])){temp = items[j - 1];items[j - 1] = items[j];items[j] = temp;}}}}static void Main(string[] args){int[] items = { 1, 2, 4, 3, 3, 13, 34, 1, 45, 9 };//使用委托BubbleSort(items, Graterthan);for(int i=0; i<items.Length; i++){Console.Write(items[i]+" ");}Console.WriteLine();BubbleSort(items, Lessthan);for (int i = 0; i < items.Length; i++){Console.Write(items[i] + " ");}}}}
概念: 使用精简的方法创建委托
分类: 语句Lambda & 表达式Lambda
结构: (形参列表) => (代码块)
BubbleSort(items,(int first,int second)=>{return first < second>//参数类型可省略: BubbleSort(items,(first,second)=>{return first < second>//单个参数Lambdavar x = data.Where( i => {return i>0;});//无参LambdaFunc<string> getUserInput =() =>{string input;do{input = Console.ReadLine();}while(intput.Trim().Length != 0);return input;}
结构: 参数 => 表达式
BubbleSort(items, (first,second) => first < second);
注意事项:
Lambda表达式没有类型
- 不能访问成员
- 不能出现在is操作的左侧
- 不能用于推断局部变量类型
- 不能在Lambda使用跳转
System.Func 代表有返回值的方法
Systen.Action 代表返回值为void的方法
//声明排序方法void BubbleSort(int[] items, Func<int, int , bool) compartsonMethod){...}