开始使用委托

委托是一种安全地封装方法的类型,它与 C 和 C++ 中的函数指针类似。与 C 中的函数指针不同,委托是面向对象的、类型安全的和保险的。委托的类型由委托的名称定义。

   1: public delegate int OutputPoint(int x, int y);


构造委托对象时,通常提供委托将包装的方法的名称或使用匿名方法。实例化委托后,委托将把对它进行的方法调用传递给方法。调用方传递给委托的参数被传递给方法,来自方法的返回值(如果有)由委托返回给调用方。这被称为调用委托。可以将一个实例化的委托视为被包装的方法本身来调用该委托。

   1: class Program
   2:     {
   3:         public delegate int OutputPoint(int x, int y);
   4:  
   5:         public static int DelegateMethod(int x, int y)
   6:         {
   7:             System.Console.WriteLine(x);
   8:             System.Console.WriteLine(y);
   9:             return x + y;
  10:         }
  11:  
  12:         static void Main(string[] args)
  13:         {
  14:             OutputPoint handler = DelegateMethod;
  15:             System.Console.WriteLine(handler(2, 3));
  16:         }
  17:     }

这会输出:

2
3
5

回调的另一个常见用法是定义自定义的比较方法并将该委托传递给排序方法。它允许调用方的代码成为排序算法的一部分。

public delegate int OutputPoint(int x, int y);
 
       public static int DelegateMethod(int x, int y)
       {
           System.Console.WriteLine(x);
           System.Console.WriteLine(y);
           return x + y;
       }
 
       public static void CallBackTest(int x, int y, OutputPoint callback)
       {
           System.Console.WriteLine(callback(x, y));
       }
 
       static void Main(string[] args)
       {
           OutputPoint handler = DelegateMethod;
           System.Console.WriteLine(handler(2, 3));
 
           OutputPoint handler1 = DelegateMethod;
           CallBackTest(1, 4, handler1);
       }

下面函数调用会输出:

1
4
5

调用委托时,它可以调用多个方法。这称为多路广播,一个方法可称为单路广播。若要向委托的方法列表(调用列表)中添加额外的方法,只需使用加法运算符或加法赋值运算符(“+”或 “+=”)添加两个委托。例如:

 
            OutputPoint handler2 = DelegateMethod;
            OutputPoint handler3 = DelegateMethod;
            OutputPoint handler4 = handler2 + handler3;
            System.Console.WriteLine(handler4(2, 3));

会输出:

2
3
2
3
5

于委托类型派生自 System.Delegate,所以可在委托上调用该类定义的方法和属性。例如,为了找出委托的调用列表中的方法数

int Count = handler4.GetInvocationList().GetLength(0);
 


作者:GangWang
出处:http://www.cnblogs.com/GnagWang/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

 
原文地址:https://www.cnblogs.com/GnagWang/p/1702727.html