当前位置: 移动技术网 > IT编程>开发语言>c# > c#中的泛型委托详解

c#中的泛型委托详解

2019年07月18日  | 移动技术网IT编程  | 我要评论

今天学习一下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中搜索元素。(没有用到过,等用到了再更新)

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网