一、Action
Action 封装的方法没有参数也没有返回值,声明原型为:
public delegate void Action();
用法:
public void Alert()
{
Console.WriteLine("这是一个警告");
}
Action t = new Action(Alert);//实例化一个Action委托
t();
如果委托的方法里的语句比较简短,也可以用Lambd表达式直接把方法定义在委托中,如下:
Action t=()=>{Console.WriteLine("这是一个警告");};
t();
二、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);
同样也可以直接用Lambd表达式直接把方法定义在委托中,代码如下:
Action<int,int>t=(a,b)=>{Console.WriteLine(a+b);};
t(2,3);
三、Func < T>
Func委托始终都会有返回值,返回值的类型是参数中最后一个,可以传入一个参数,也可以最多传入16个参数,但可以传入最多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);
同样也可以直接用Lambd表达式直接把方法定义在委托中,代码如下:
Func<int,int,bool>t=(a,b)=>{return a>b;};
bool result = t(2,3);
四、Predicate < T >
Predicate<T>委托表示定义一组条件并确定指定对象是否符合这些条件的方法,返回值始终为bool类型,声明原型为:
public delegate bool Predicate<int 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的第一个元素
总结
- 如果要委托的方法没有参数也没有返回值就想到
Action - 有参数但没有返回值就想到
Action<T> - 无参数有返回值、有参数且有返回值就想到
Func<T> - 有bool类型的返回值,多用在比较器的方法,要委托这个方法就想到用
Predicate<T>
例子
List<int> arr_Int = new List<int>() { 1, 2, 23, 42, 33, 221, 213 };
bool bIsExist = arr_Int.Exists(n => n > 250);
int c = arr_Int.Find(n => n == 2);
int nFirst = arr_Int.First<int>();
arr_Int.ForEach(n => {});
arr_Int.Insert(1, 11111);
arr_Int.Reverse();
List<int> INTArr = arr_Int.Select((n, Tresult) => Tresult = n).ToList();
arr_Int.Single(n=>n==23);
var query = (from i in arr_Int
where i > 1111
select i).ToArray();
本文详细介绍了C#中Action、Func和Predicate三种常用委托的使用方法,包括它们的基本概念、参数及返回值特点,并通过具体示例展示了如何使用Lambda表达式来简化代码。

643

被折叠的 条评论
为什么被折叠?



