代码改变世界

c#基础 委托

2013-04-25 21:45  Mike.Jiang  阅读(213)  评论(0)    收藏  举报

1 概述

委托:公共语言运行库为支持方法回调而实现的一种技术。即可以用委托封装一个方法的引用,然后可以将方法作为参数传递。在.NET中支持一个委托可以同时指向多个方法。

2 示例

View Code
    public class Light
    {
        public string Name { get; set; }

        public void OnFlip(string status) 
        {
            Console.WriteLine(string.Format("{0} is {1} now",this.Name,status));
        }
    }


public delegate void FlipDelegate(string status);
    public class Switch
    {
        public void FlipDown(FlipDelegate flipDele) 
        {
            flipDele("On");
        }
        
        public void FlipUp(FlipDelegate flipDele) 
        {
            flipDele("Off");
        }

        public void FlipDown2(Action<string> action)
        {
            action("On");
        }

        public void FlipUp2(Action<string> action)
        {
            action("Off");
        }
    }

 public class Class1
    {
        [Test]
        public void Test1() 
        {
            Light light1 = new Light();
            light1.Name = "light1";

            Light light2 = new Light();
            light2.Name = "light1";

            Switch s = new Switch();
            FlipDelegate flipDele = new FlipDelegate(light1.OnFlip);
            flipDele += new FlipDelegate(light2.OnFlip);

            flipDele.GetInvocationList();
            s.FlipDown(flipDele);

            s.FlipUp(flipDele);

            Console.ReadLine();
        }
        [Test]
        public void Test2()
        {
            Light light1 = new Light();
            light1.Name = "light1";

            Switch s = new Switch();
            Action<string> action = new Action<string>(light1.OnFlip);
            s.FlipDown2(action);

            s.FlipUp2(action);

            Console.ReadLine();
        }
    }

3委托实现细节

编译器在编译委托声明时,实际上是从System.MulticastDelegate类派生出一个新类

 

其中.ctor(Object,InPrt),第一个参数指向委托的目标对象,如果委托的是静态方法,目标对象为NULL;第二个参数是对方法的引用。

最后对于委托理解,仅即于应用,待有更深入的理解时,再更新此文。