zhixin's profileMYspace.comPhotosBlogLists Tools Help

Blog


    January 23

    C# 委托

    委托,顾名思义,就是中间代理人的意思。C#中的委托允许你将一个对象中的方法传递给另一个能调用该方法的类的某个对象。你可以将类A中的一个方法m(被包含在某个委托中了)传递给一个类B,这样类B就能调用类A中的方法m了。同时,你还可以以静态(static)的方式或是实例(instance)的方式来传递该方法。所以这个概念和C++中的以函数指针为参数形式调用其他类中的方法的概念是十分类似的。
    1. 声明一个委托对象,其参数形式一定要和你想要包含的方法的参数形式一致。
    2. 定义所有你要定义的方法,其参数形式和第一步中声明的委托对象的参数形式必须相同。
    3. 创建委托对象并将所希望的方法包含在该委托对象中。  
    4. 通过委托对象调用包含在其中的各个方法。

     public class ClassMethod
        {
            //定义被调用类的方法
            public void delegateMethod1(string input)
            {
                System.Web.HttpContext.Current.Response.Write
                    (string.Format("This is delegateMethod1 and the input to the method is {0}",input));
            }
            public void delegateMethod2(string input)
            {
                System.Web.HttpContext.Current.Response.Write (string.Format(
                "This is delegateMethod2 and the input to the method is {0}",
                input));
            }
        }

    *******************************


        // 声明一个委托对象
        public delegate void MyDelegate(string input);

        public class Class3
        {
            //创建委托对象并将上面的方法包含其中
             public MyDelegate createDelegate()
             {
                    ClassMethod c2 = new ClassMethod();
                    MyDelegate d1 = new MyDelegate(c2.delegateMethod1);
                    MyDelegate d2 = new MyDelegate(c2.delegateMethod2);
                    MyDelegate d3 = d1 + d2;
                    return d3;
            }

             //调用它类的方法
             public void callDelegate(MyDelegate d, string input)
             {
                 d(input);
             }
        }

    ********************************

     protected void Page_Load(object sender, EventArgs e)
            {
              //页面调用
                Class3 c3 = new Class3();
                MyDelegate d=c3.createDelegate();
                c3.callDelegate(d,"Calling the delegate");
            }

    More http://www.linux-cn.com/html/program/aspnet/20070604/49717.html