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#实现检索不区分大小写并高亮显示的示例代码分享

详情介绍C#中winform实现多线程异步更新ui的示例代码

详解C#创建dll类库的方法分享(图文)

C#中文转拼音without cjk的代码分享

C# 带滚动条的label控件的示例代码详解

c#中的arraylist是什么?

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

详解C#中抽象类与接口的区别

unity实现脚本插件[script create dialog]图文详解

详解C#把unicode编码转换为gb编码的示例代码

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




打赏

取消

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

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

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

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

评论

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