博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#_delegate - 有返回值手工调用
阅读量:7116 次
发布时间:2019-06-28

本文共 2027 字,大约阅读时间需要 6 分钟。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace EventClock{    public class ClassWithDelegate    {         //封装了一个返回值为int的多重委托方法        public delegate int DelegateThatReturns();        public DelegateThatReturns theDelegate;        public void Run()        {            for (; ; )            {                Thread.Sleep(500);                if (theDelegate != null)                {                    //显式调用每个委托方法                    foreach (DelegateThatReturns del in theDelegate.GetInvocationList())                    {                        int result = del();                        Console.WriteLine("Delegates fired! return result: {0}",result);                    }                    Console.WriteLine();                }            }        }    }    public class FirstSubscribe    {        private int myCounter = 0;        public void Subscribe(ClassWithDelegate theClassWithDelegate)        {            theClassWithDelegate.theDelegate += new ClassWithDelegate.DelegateThatReturns(DisplayCounter);        }        public int DisplayCounter()        {            return ++myCounter;        }    }    public class SecondSubscribe    {        private int myCounter = 0;        public void Subscribe(ClassWithDelegate theClassWithDelegate)        {            theClassWithDelegate.theDelegate += new ClassWithDelegate.DelegateThatReturns(Doubler);        }        public int Doubler()        {            return myCounter += 2;        }    }        class Program    {        static void Main(string[] args)        {            ClassWithDelegate theClassWithDelegate = new ClassWithDelegate();            FirstSubscribe fs = new FirstSubscribe();            fs.Subscribe(theClassWithDelegate);            SecondSubscribe ss = new SecondSubscribe();            ss.Subscribe(theClassWithDelegate);            theClassWithDelegate.Run();                        Console.ReadLine();        }    }}

转载于:https://www.cnblogs.com/MarchThree/p/3720444.html

你可能感兴趣的文章
【安全牛学习笔记】MsSQL高级注入
查看>>
重定向和管道
查看>>
python初体验
查看>>
GIT在master如何回退到历史版本
查看>>
freecodecamp新手自己写的第一个网页
查看>>
Android SDK Web SDK 接口测试总结
查看>>
编写原生的Node.js模块
查看>>
18:再议python中的print——格式化输出
查看>>
sql使用索引原则
查看>>
文件下载
查看>>
通过iec61850协议访问设备数据的一个例子
查看>>
远离框架,实现自己REST风格的Servlet框架(二)
查看>>
记CentOS7一个百万PV商城的测试
查看>>
Kafka无法消费!?究竟是bug的“沦陷”还是配置的“扭曲”?
查看>>
eyoucms uihtml 带html富文本可视化标签
查看>>
JSP常用指令
查看>>
SAMBA服务的搭建和访问
查看>>
APP推广 | 如何利用免费渠道去推广
查看>>
功能发布:大数据驱动业务决策,CDN实时日志重磅上线
查看>>
Vue实现环形进度条方法组件
查看>>