关于委托delegate的几点

本文详细探讨了C#中委托的定义、基本使用、多播能力及其实现方式,包括委托实例化、调用过程以及与接口的区别。通过具体示例展示了委托如何在多个方法间传递和调用,以及如何选择使用委托或接口来解决特定问题。同时,解释了委托的参数兼容性、返回值兼容性和类型兼容性的概念,并提供了相关代码示例。

##**

1.委托delegate一般表达式**:

delegate return-Type delegateName (parameters)
eg:
   //1.declare a delegate
   public delegate Tranform(int x);

   public static int Square(int x) {return x*x};

   //2.instaniated delegate
   Tranform t = Square;
   //shorten for Tranform t = new Tranform(Square); 

   //3.Invocation delegate
   int result = t(3);// result = 9

2.使用委托的三个步骤如上面例子

Declaration delegate
Instaniation delegate
Invocation delegate

委托一般理解为C语言中,指向方法的指针

3.MultiDelegate
所有委托实例都有一对多的能力(multicast capability),也就是可以引用多个目标方法(target methods),+= 和-=运算符重载

eg1:
SomeDelegate d = SomeMethod1;
d += SomeMethod1;//d = SomeMethod1 + SomeMethod2;
调用d将按添加顺序依次调用SomeMethod1和SomeMethod2

eg2:
SomeDelegate d = null ;
d += SomeMethod1;// when d is null, d = SomeDelegate 

所有delegates类型都隐式的继承于System.MultiDelegate,这个又继承自System.Delegate

eg:
public delegate void ProcessReporter(int percentComplete);
public class Util
{
   public static void HardWork(ProcessReporter p)
    {
         for(i = 0 ; i < 10; i ++ )
           {
                p(i*10); //Invoke delegate
                System.Threading.Thread.Sleep(1000);//simulate hard work           
          }   
   } 
}
class Test 
{
   static void Main()
   {
   ProcessReporter p = WriteProcessToConsole;
   p += WriteProcessToFile;
   Util.HardWork(p);
   }

   static void WriteProcessToConsole(int precentComplete)
   { Console.Writeline(precentComplete);}
   static void WriteProcessToFile(int precentComplete)
   {System.IO.WriteAllText("process.txt",precentComplete.ToString());}
}

4. Generic Delegate
一般模型:

public delegate T Transform<T>(T arg)

5委托和接口的选择原则
在解决问题时,用委托或接口都可以解决,一般满足以下一些要求时选用委托:
1.接口只定义一个方法时
2.Multicast 的能力被需要时
3.订阅者(the subscribers)需要实现接口多次时

> eg:
> class Squarer : ITransformer
{
public int Transform (int x) { return x * x; }
}
class Cuber : ITransformer
{
public int Transform (int x) {return x * x * x; }
}
...
static void Main()
{
int[] values = { 1, 2, 3 };
Util.TransformAll (values, new Cuber());
foreach (int i in values)
Console.WriteLine (i);
}
接口只有一个方法,并且需要调用接口多次,这个时候选用delegate更加的方便

6.委托的兼用性(delegate compatibility)多态的表现
1.parameter compatibility
委托参数比目标方法参数更加的精确,这叫做contravariance
(a delegate can have more specific parameter types than its
method target. This is called contravariance)

eg
delegate void StringAction(string s);
class Test
{
  static void Main()
  {
   StringAction sa = new StringAction (ActOnObject);
   sa ("hello");
   }
   **static void ActionObject (object o)**
   {
    Console.WriteLine (o); // hello
    }
}
参数隐式的从string转变成object

2 Return Type Comptibility
目标方法返回的类型比委托要求的更精确,这叫做covariance
( a delegate target method may return a more specific type than described by the delegate. This is called covariance.)

    eg:
delegate object ObjectRetriever();
class Test
{
  static void Main()
 {
 ObjectRetriever o = new ObjectRetriever (RetriveString);
 object result = o();
 Console.WriteLine (result); // hello
 }
 static string RetriveString() { return "hello"; }
}

3.类型兼容性(Type Compability)
a.委托类型相互之间都互不兼容,即使他们的签名一样

    delegate void D1();
    delegate void D2();
    ...
    D1 d1 = Method1;
    D2 d2 = d1; // Compile-time error
    D2 d2 = new D2(d1); //permitted

b.委托实例如果目标方法一样则可以认为相等(equal)

  ...
  D d1 = Method1;
  D d2 = Method1;
  Console.WriteLine (d1 == d2); // True

c.多重委托他们以相同的顺序引用相同目标方法时可以认为相等
Multicast delegates are considered equal if they reference the same methods in the same order.

7.Func和Action委托 (泛型委托)
Func用法:(in 表示的是委托参数,这里只是起到标注的作用,实际不存在)
out 表示的是委托返回类型,同in一样作标识)
delegate TResult Func ();//只有返回类型,可以为void
delegate TResult Func

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值