服务器之家

服务器之家 > 正文

c#中的泛型委托详解

时间:2021-12-20 14:34     来源/作者:WhiteTaken

今天学习一下c#中的泛型委托。

1.一般的委托,delegate,可以又传入参数(<=32),声明的方法为  public delegate void somethingdelegate(int a);

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
namespace delegatesummary {
 public delegate void getintdelegate(int a); //声明一个委托
 public class getintclass {
 public static void setdelegatestring(int a,getintdelegate getintdelegate) {//使用委托
  getintdelegate(a);
 }
 public void getint1(int a) { //方法1
  console.writeline("getint1方法调用,参数为:" + a);
 }
 public void getint2(int a) { //方法2
  console.writeline("getint2方法调用,参数为:" + a);
 }
 }
 class program {
 static void main(string[] args) {
  getintclass gc=new getintclass();
  getintclass.setdelegatestring(5, gc.getint1);  //方法1,2作为委托的参数
  getintclass.setdelegatestring(10, gc.getint2);
  console.writeline("=====================");
  getintdelegate getintdelegate;
  getintdelegate = gc.getint1;     //将方法1,2绑定到委托
  getintdelegate += gc.getint2;
  getintclass.setdelegatestring(100, getintdelegate);
  console.read();
 }
 }
}

输出结果,注意两种方式的不同,第一种将方法作为委托的参数,第二种是将方法绑定到委托。

c#中的泛型委托详解

2.泛型委托之action,最多传入16个参数,无返回值。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
namespace delegatesummary {
 class program {
 static void main(string[] args) {
  testaction<string>(getstring, "whitetaken"); //传入方法
  testaction<int>(getint, 666);
  testaction<int, string>(getstringandint, 666, "whitetaken");
  console.read(); 
 }
 public static void testaction<t>(action<t> action,t p1) {        //action传入一个参数测试
  action(p1);
 }
 public static void testaction<t, p>(action<t, p> action, t p1, p p2) { //action传入两个参数测试
  action(p1,p2);
 }
 public static void getstring(string a) {    //实现int类型打印
  console.writeline("测试action,传入string,并且传入的参数为:" +a);
 }
 public static void getint(int a) {     //实现string类型打印
  console.writeline("测试action,传入int,并且传入的参数为:" + a);
 }
 public static void getstringandint(int a, string name) {    //实现int+string类型打印
  console.writeline("测试action,传入两参数,并且传入的参数为:" + a+":"+name);
 }
 }
}

测试结果:

c#中的泛型委托详解

3.泛型委托之func,最多传入16个参数,有返回值。(写法与action类似,只是多了返回值)

4.泛型委托之predicate(不是很常用),返回值为bool,用在array和list中搜索元素。(没有用到过,等用到了再更新)

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持服务器之家!

原文链接:http://www.cnblogs.com/WhiteTaken/p/6293063.html

标签:

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部