打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C# 委托链(多播委托)

C# 委托链(多播委托)

委托既可以封装一个方法,又可以对同一类型的方法进行封装,它就是多播委托

复制代码

 1 using System;

 2 using System.Collections.Generic;

 3 using System.Linq;

 4 using System.Text;

 5 

 6 namespace DelegateTest

 7 {

 8     class Program

 9     {

10         //申明一个委托类型,它的实例引用一个方法

11         //该方法传递0参数,返回void类型

12         public delegate string DelegateTestOne();

13 

14         static void Main(string[] args)

15         {

16             //用静态方法来实例化委托

17             DelegateTestOne teststatic = new DelegateTestOne(Program.method1);

18 

19             //用实例方法来实例化委托

20             DelegateTestOne test2 = new DelegateTestOne(new Program().method2);

21 

22             //用实例方法来实例化委托

23             DelegateTestOne test3 = new DelegateTestOne(new Program().method3);

24 

25             //定义空一个委托对象

26             DelegateTestOne deleteAll = null;

27             deleteAll += teststatic;

28             deleteAll += test2;

29             deleteAll += test3;

30             Console.WriteLine(Test(deleteAll));

31 

32             Console.ReadLine();

33         }

34 

35 

36         public static string method1()

37         {

38 

39             //Console.WriteLine("这是一个静态方法");

40             return "这是一个静态方法";

41         }

42 

43         public string method2()

44         {

45             //Console.WriteLine("这是实例方法2");

46             return "这是实例方法2";

47         }

48 

49         public string method3()

50         {

51            // Console.WriteLine("这是实例方法3");

52             return "这是实例方法3";

53         }

54 

55 

56         //测试多播委托

57         public static string Test(DelegateTestOne testone)

58         {

59             if (testone == null)

60             {

61                 return null;

62             }

63             StringBuilder returnstring = new StringBuilder();

64 

65             Delegate[] delegatearray = testone.GetInvocationList();

66 

67             foreach (DelegateTestOne t in delegatearray)

68             {

69                 try

70                 {

71                     returnstring.Append(t() + Environment.NewLine);

72                 }

73                 catch (Exception e)

74                 {

75 

76                 }

77             }

78             //把结果返回给调用者

79             return returnstring.ToString();

80         }

81 

82     }

83 }

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C#中的delegate
使用委托(C# 编程指南)
Delegate委托之学习心得
C# =>符号的使用
c#
C# 委托(Delegate) | 菜鸟教程
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服