本文主要介绍了c#中的泛型委托。具有很好的参考价值,下面跟着小编一起来看下吧
今天学习一下c#中的泛型委托。
1.一般的委托,delegate,可以又传入参数(<=32),声明的方法为 public delegate void somethingdelegate(int a);
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();
}
}
}
输出结果,注意两种方式的不同,第一种将方法作为委托的参数,第二种是将方法绑定到委托。
2.泛型委托之action,最多传入16个参数,无返回值。
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);
}
}
}
测试结果:
3.泛型委托之func,最多传入16个参数,有返回值。(写法与action类似,只是多了返回值)
4.泛型委托之predicate(不是很常用),返回值为bool,用在array和list中搜索元素。(没有用到过,等用到了再更新)
以上就是c#中泛型委托的示例代码分享(图)的详细内容。