zoukankan      html  css  js  c++  java
  • 委托使用(2)

    class ClassWithDelegate    

    {    

        public delegate int DelegateThatReturnsInt();        

        public DelegateThatReturnsInt theDelegate;    

        public void Run()     

       {        

               for (; ; )      

             {     

                     Thread.Sleep(500);

                     if (theDelegate != null)

                    {//第一个方法DisplayCounter()(由FirstSubscriber调用),返回1,2,3,4,5.但是这些值都将被第二个方法返回的值所覆盖 

                       //我的目的是依次显示每个方法调用的结果。为此,必须接管多重委托所封装方法调用的职责。

                        foreach (DelegateThatReturnsInt del in theDelegate.GetInvocationList())

                        {

                            int result = del();

                            Console.WriteLine("Delegate fired! Returned result:{0}", result.ToString());

                        }

                        Console.WriteLine();

                    }

                }

            }

    }

        class FirstSubscriber

        {

            private int myCounter = 0;

            public void Subscribe(ClassWithDelegate theClassWithDelegate)

            {

                theClassWithDelegate.theDelegate += new ClassWithDelegate.DelegateThatReturnsInt(DisplayCounter);//委托实例化                                        //theClassWithDelegate.theDelegate +=DisplayCounter可以写成这样

                //也可以之间用匿名过程,可以把DisplayCounter()函数去掉

                // theClassWithDelegate.theDelegate +=delegate()

                //{

                //      return ++myCounter;

                // };

            }

            public  int DisplayCounter()

            {

                return ++myCounter;

            }

        }

        class SecondSubscriber

        {

            private int myCounter = 0;

            public void Subscriber1(ClassWithDelegate theClassWithDelegate)

            {

                theClassWithDelegate.theDelegate += new ClassWithDelegate.DelegateThatReturnsInt(DisplayCounter1);//委托实例化

            }

            public int DisplayCounter1()

            {

                return myCounter += 2;

            }

        }

    ClassWithDelegate classWithDelegate = new ClassWithDelegate();

    FirstSubscriber firstSubscriber = new FirstSubscriber();            

    firstSubscriber.Subscribe(classWithDelegate);            

    SecondSubscriber secondSubscriber = new SecondSubscriber();            

    secondSubscriber.Subscriber1(classWithDelegate);                       

    classWithDelegate.Run();

  • 相关阅读:
    Solution: Win 10 和 Ubuntu 16.04 LTS双系统, Win 10 不能从grub启动
    在Ubuntu上如何往fcitx里添加输入法
    LaTeX 笔记---Q&A
    Hong Kong Regional Online Preliminary 2016 C. Classrooms
    Codeforces 711E ZS and The Birthday Paradox
    poj 2342 anniversary party
    poj 1088 滑雪
    poj 2479 maximum sum
    poj 2481 cows
    poj 2352 stars
  • 原文地址:https://www.cnblogs.com/gull/p/1857803.html
Copyright © 2011-2022 走看看