对于委托,我这小菜鸟的理解。

委托是什么,这个个人有个人的理解方式。

我的理解方式就是它是一个中间商。

为什么这么说,待我用代码来解释。

委托奸商类:

 1         /// <summary>
 2         /// 委托中间人
 3         /// </summary>
 4         public class DeleageteT
 5         {
 6             /// <summary>
 7             /// 定义一个委托,我能做的某一类事。
 8             /// </summary>
 9             /// <param name="text"></param>
10             public delegate void woshiweituo(string text);
11 
12             /// <summary>
13             /// 定义一个事件,谁要委托我啊!赶紧来!
14             /// </summary>
15             public event woshiweituo woshishijian;
16 
17             /// <summary>
18             /// 定义一个开始方法,我可不知道什么时候开始干活,你要告诉哦!
19             /// </summary>
20             /// <param name="text"></param>
21             public void StarDelegate(string text)
22             {
23                 if (woshishijian != null)
24                 {
25                     //执行注册中的事件。
26                     woshishijian(text);
27                 }
28                 else
29                 {
30                     Console.WriteLine("都没注册事件,托毛啊!");
31                 }
32             }
33         }

一堆委托人:

        /// <summary>
        /// 我是第一个委托人
        /// </summary>
        public class Implementation1
        {
            public void show(string text)
            {
                Console.WriteLine("{0}{1}", text, this.GetType().Name);
            }
        }

        /// <summary>
        /// 我是第二个委托人
        /// </summary>
        public class Implementation2
        {
            public void show(string text)
            {
                Console.WriteLine("{0}{1}", text, this.GetType().Name);
            }
        }

        /// <summary>
        /// 我是第三个委托人
        /// </summary>
        public class Implementation3
        {
            public void show(string text)
            {
                Console.WriteLine("{0}{1}", text, this.GetType().Name);
            }
        }

开始啦!

 1         static void Main()
 2         {
 3             //第一个委托人
 4             Implementation1 i1 = new Implementation1();
 5             //第二个委托人
 6             Implementation2 i2 = new Implementation2();
 7             //第三个委托人
 8             Implementation3 i3 = new Implementation3();
 9 
10             //奸商来了!
11             DeleageteT delegetes = new DeleageteT();
12 
13             //赶紧注册吧!
14             delegetes.woshishijian += i1.show;
15             delegetes.woshishijian += i2.show;
16             delegetes.woshishijian += i3.show;
17 
18             //奸商开始干活了
19             delegetes.StarDelegate("我的名字是:");
20 
21             Console.ReadKey();
22         }

图:。。。。

如果没错的话,本例子里面的是多播委托。对于多播委托只能用关键字void。为什么?百度吧。。。。

众位有什么见解,希望能提出来,我们共同进步,求大神指点。。。。

 

posted @ 2016-12-30 15:58  Stupid_Bire  阅读(252)  评论(0编辑  收藏  举报