多播委托

下面这个多播委托实例是根据自己所掌握的多播委托所写的一个例子,相当简单。为了验证多播委托理论,采用了依次使用加,乘,减,除,利用理论猜想最终的结果,如果按照理论推想正确则说明多播是按某种原则执行。简言之:多播是对委托方法依次执行。

以下是代码:

using System;

namespace DelegateTest02
{
    class Program
    {
        public delegate void CountNumber(int i, int j);
        public static int result = 0;
        static void Main(string[] args)
        {
            //以下开始为多播委托
            Program P = new Program();
           //3,1 第1次委托方法为加结果3+1=4
            CountNumber C1 = P.Method1;
            //3,1 第2次委托方法为乘结果4+3*1=7
            CountNumber C2 = P.Method2;
           //3,1 第3次委托方法为减结果4+3*1+(3-1)=9
            CountNumber C3 = P.Method3;
            //3,1 第4次委托方法为减结果4+3*1+(3-1)+3/1=12
            CountNumber C4 = P.Method4;
           //以下为开始多播委托“叠加”,类似两数叠加
            CountNumber C5 = C1 + C2;
            C5 += C3;
            C5 += C4;

            //C5 为C1,C2,C3,C4 多播委托,依次执行委托C1,C2,C3,C4 然后结果叠加,根据以上分析预期结果为12
            C5(3, 1);
            Console.WriteLine("3,1 两数依次进行【加,乘,减,除】后的结果为:" + result);
            Console.ReadKey();
        }
        public void Method1(int i, int j)
        {
            result += (i + j);
        }
        public void Method2(int i, int j)
        {
            result += (i * j);
        }
        public void Method3(int i, int j)
        {
            result += (i - j);
        }
        public void Method4(int i, int j)
        {
            result += (i / j);
        }
    }
}

关于委托多播的注意点:

多播委托可以连续调用多个方法。
1.委托声明返回值必须为void;
2.使用“+”、“+=”添加方法,“-”、“-=”删除方法。

该实例的最终效果为:

 

.......

posted @ 2012-05-09 15:08  lb_yy  阅读(109)  评论(0)    收藏  举报