zoukankan      html  css  js  c++  java
  • C#_delegate

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


  • 相关阅读:
    Linux网络编程头文件汇总
    CentOS7.6 源码安装 libxml2-2.8.0
    CentOS7.6 源码安装 glib-2.30.3
    CentOS7.6 源码安装 libevent-2.1.8-stable
    CentOS7.6 源码安装 zeromq-4.2.5
    CentOS7.6 源码安装 go1.13.12
    CentOS7.6 源码安装 openssl-1.1.1c
    CentOS7.6 源码安装 Python-3.7.4
    Go学习笔记:Linux下安装Go语言
    Go学习笔记:初识Go语言
  • 原文地址:https://www.cnblogs.com/MarchThree/p/3720444.html
Copyright © 2011-2022 走看看