谁能写个例子来解释下使用委托的3个步骤,
1.声明委托
2.实例化委托
3.调用委托
感觉自己还是不理解我晕!

解决方案 »

  1.   

    http://www.jpinw.com/teach/bc/CVBJAVA/200806/1240195.html
      

  2.   

    http://www.cnblogs.com/finesite/articles/255884.html
      

  3.   

    给你个简单的两个数相加的例子:
    using System;
    namespace Add
    {
        delegate void numberAdd(int a, int b);  //声明委托
        class program
        {
            static void Main()
            {
                numberAdd n1 = delegate(int a, int b)  //实例化委托对象,委托是引用类型。
                {
                    Console.WriteLine(a + b);
                };
                int x = int.Parse(Console.ReadLine());
                int y = int.Parse(Console.ReadLine());
                n1(x, y);
                Console.ReadLine();
            }
        }
    }要是你有C++的经验,委托就很好理解,就是函数指针。通俗点就是,函数的形参是函数。
      

  4.   

    我的理解,在.NET中委托就是一种特殊的接口。特殊之处还不清楚。
    事件是委托的实例。
    接口是一种特殊的抽象类。
      

  5.   


    // keyword_delegate2.cs
    // Calling both static and instance methods from delegates
    using System;// delegate declaration
    delegate void MyDelegate();public class MyClass 
    {
       public void InstanceMethod() 
       {
          Console.WriteLine("A message from the instance method."); 
       }   static public void StaticMethod() 
       {
          Console.WriteLine("A message from the static method.");
       }
    }public class MainClass 
    {
       static public void Main() 
       {
          MyClass p = new MyClass();      // Map the delegate to the instance method:
          MyDelegate d = new MyDelegate(p.InstanceMethod);
          d();      // Map to the static method:
          d = new MyDelegate(MyClass.StaticMethod);
          d();
       }
    }
      

  6.   

    一楼的兄弟一语道破天机,呵呵
    在c++里函数名就是这个函数的地址的指针,可以直接把一个函数名作为参数传给另一个函数,并在那个函数里面执行!
    c#的指针一般是托管的,不能这样用,为了解决这个问题呢就用了委托这个东西。
    ----------------------
    1.声明委托 
    2.实例化委托 
    3.调用委托 
    ----------------------
    声明委托就说定一个类型的函数的指针(也就是说函数的声明形式和这个委托的声明形式一致)如,
    // Declare delegate -- defines required signature:
    delegate void SampleDelegate(string message);
    这就说明,凡是返回值类型void,参数类型为string的函数都可以有找个委托代理,如,
        // Regular method that matches signature:
        static void SampleDelegateMethod(string message)
        {
            Console.WriteLine(message);
        }
    ===========
    实例化委托,这一步不用解释了吧
            // Instantiate delegate with named method:
            SampleDelegate d1 = SampleDelegateMethod;
    ===========
    调用委托,把实例话之后的委托当你定义的那个函数一样调用就可以了
    // Invoke delegate d1:
            d1("Hello");
    ===============End=====================
    另外:匿名方法
    实例化
            // Instantiate delegate with anonymous method:
            SampleDelegate d2 = delegate(string message)
            { 
                Console.WriteLine(message); 
            };
    调用
           // Invoke delegate d2:
            d2(" World");
      

  7.   

    强烈楼主看这篇博客,很经典
    http://www.cnblogs.com/JimmyZhang/archive/2007/09/23/903360.html