原博链接:http://www.cnblogs.com/maitian-lf/p/3671782.html
CLR环境中给我们内置了几个常用委托Action、 Action<T>、Func<T>、Predicate<T>,一般我们要用到委托的时候,尽量不要自己再定义一 个委托了,就用系统内置的这几个已经能够满足大部分的需求,且让代码符合规范。
1、Action
Action封装的方法没有参数也没有返回值,声明原型为:
public delegate void Action();
用法如下:
public void Alert()
{
Console.WriteLine("这是一个警告");
}
Action t = new Action(Alert); // 实例化一个Action委托
t();
2、Action<T>
Action<T>是Action的泛型实现,也是没有返回值,但可以传入最多16个参数,两个参数的声明原型为:
public delegate void Action<in T1, in T2>(T1 arg1, T2 arg2);
用法如下:
private void ShowResult(int a, int b)
{
Console.WriteLine(a + b);
}
Action<int, int> t = new Action<int, int>(ShowResult);//两个参数但没返回值的委托
t(2, 3);
3、Func<T>
Func<T>委托始终都会有返回值,返回值的类型是参数中最后一个,可以传入一个参数,也可以最多传入16个参数,两个参数一个返回值的声明原型为:
public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
用法如下:
public bool Compare(int a, int b)
{
return a > b;
}
Func<int, int, bool> t = new Func<int, int, bool>(Compare);//传入两个int参数,返回bool值
bool result = t(2, 3);
4、Predicate<T>
Predicate<T>委托表示定义一组条件并确定指定对象是否符合这些条件的方法,返回值始终为bool类型,声明原型为:
public delegate bool Predicate<in T>(T obj);
用法如下:
public bool Match(int val)
{
return val > 60;
}
Predicate<int> t = new Predicate<int>(Match); //定义一个比较委托
int[] arr = { 13, 45, 26, 98, 3, 56, 72, 24 };
int first = Array.Find(arr, t); //找到数组中大于60的第一个元素
直接用Lambd表达式直接把方法定义在委托中,代码如下:
Predicate<int> t = val => { return val > 60;}; //定义一个比较委托
int[] arr = { 13, 45, 26, 98, 3, 56, 72, 24 };
int first = Array.Find(arr, t); //找到数组中大于60的第一个元素
其中Array数组类中的find()的第二个参数是委托类型,表明arr的元素被逐个传递给 Predicate,与条件匹配的元素则保存在返回值中。
上述场合应用中,其实不必显式创建 Predicate<T> 委托,编译器会通过上下文推知正确的委托,并自动创建委托。所以关于Array.Find()方法中委托参数的使用可以变为:
public bool Match(int val)
{
return val > 60;
}
int[] arr = { 13, 45, 26, 98, 3, 56, 72, 24 };
int first = Array.Find(arr, Match); //自动创建委托
或者:
int[] arr = { 13, 45, 26, 98, 3, 56, 72, 24 };
int first = Array.Find(arr,val => { return val > 60;}); //自动创建委托