CLR环境中给我们内置了几个常用委托Action、 Action
一、Action
Action封装的方法没有参数也没有返回值,声明原型为:
1 public delegate void Action();
用法如下:
1 public void Alert()
2 {
3 Console.WriteLine("这是一个警告");
4 }
5
6 Action t = new Action(Alert); // 实例化一个Action委托
7 t();
如果委托的方法里的语句比较简短,也可以用Lambd表达式直接把方法定义在委托中,如下:
1 Action t = () => { Console.WriteLine("这是一个警告"); };
2 t();
二、Action
Action
1 public delegate void Action
用法如下:
1 private void ShowResult(int a, int b)
2 {
3 Console.WriteLine(a + b);
4 }
5
6 Action
7 t(2, 3);
同样也可以直接用Lambd表达式直接把方法定义在委托中,代码如下:
1 Action
2 t(2, 3);
三、Func
Func
1 public delegate TResult Func
用法如下:
1 public bool Compare(int a, int b)
2 {
3 return a > b;
4 }
5
6 Func
7 bool result = t(2, 3);
同样也可以直接用Lambd表达式直接把方法定义在委托中,代码如下:
1 Func
2 bool result = t(2, 3);
四 、Predicate
Predicate
1 public delegate bool Predicate
用法如下:
1 public bool Match(int val)
2 {
3 return val > 60;
4 }
5
6 Predicate
7 int[] arr = { 13, 45, 26, 98, 3, 56, 72, 24 };
8 int first = Array.Find(arr, t); //找到数组中大于60的第一个元素
同样也可以直接用Lambd表达式直接把方法定义在委托中,代码如下:
1 Predicate
2 int[] arr = { 13, 45, 26, 98, 3, 56, 72, 24 };
3 int first = Array.Find(arr, t); //找到数组中大于60的第一个元素
总结:
如果要委托的方法没有参数也没有返回值就想到Action
有参数但没有返回值就想到Action
无参数有返回值、有参数且有返回值就想到Func
有bool类型的返回值,多用在比较器的方法,要委托这个方法就想到用Predicate
参考文章
发表评论