c#中泛型委托的示例代码分享(图)


本文摘自PHP中文网,作者黄舟,侵删。

本文主要介绍了c#中的泛型委托。具有很好的参考价值,下面跟着小编一起来看下吧

今天学习一下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();

 }

 }

}

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

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);

 }

 }

}

测试结果:

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

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

以上就是c#中泛型委托的示例代码分享(图)的详细内容!

相关阅读 >>

C#接口(interface)

C#接口的实例详解

C#中backgroundworker用法的详解(图)

怎样用C#打印一个n行的菱形?实战详解

bitmap生成base64码(C#

C#开发实例-订制屏幕截图工具(九)使用自定义光标和qq截图时的光标(图)

C#实现在listview中插入图片的示例代码分享

C#遍历文件夹子目录下所有图片及遍历文件夹下的文件代码分享

C# .net 将list序列化

详解C#实现获取汉字十六进制unicode编码字符串的示例代码

更多相关阅读请进入《C#》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...