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

  • 相关阅读:
    我劝你不要记账
    富人不存钱
    1w+的心路历程
    简历这么写才对!
    Android 开发凉了吗!
    三个思维转变
    说一说赚钱
    【原】Effective Objective-C 2.0 编写高质量iOS与OS X代码的52个有效方法(Matt Galloway著)读书笔记(二)
    【原】Effective Objective-C 2.0 编写高质量iOS与OS X代码的52个有效方法(Matt Galloway著)读书笔记(一)
    【原】iOS开发进阶(唐巧)读书笔记(二)
  • 原文地址:https://www.cnblogs.com/gull/p/1857803.html
Copyright © 2011-2022 走看看