<C# 6.0 & .NET 4.6 Framework>

来源:互联网 发布:郑州淘宝网店加盟查封 编辑:程序博客网 时间:2024/06/14 07:14

Chapter 10: Delegates, Events and Lambda Expressions


這個東西叫委託。當定義一個委託的時候,編譯器在後面會聲明一個同名密封類,並繼承自System.MulticastDelegate。它的結構也是固定的,有固定的一些方法。

public sealed class MyOtherDelegate : System.MulticastDelegate{public string Invoke(out bool a, ref bool b, int c);public IAsyncResult BeginInvoke(out bool a, ref bool b, int c, AsyncCallback cb, object state);public string EndInvoke(out bool a, ref bool b, IAsyncResult result);}

其中BeginInvoke()的参数表和你声明的委托的参数表是相同的,而EndInvoke()的返回类型和委托的返回类型是相同的。

还有要注意的就是委托是能够接受out和ref参数的。


你自己不能直接声明MulticastDelegate的子类,这样会导致编译错误,不过,对于你声明的委托类型的对象,你却能够在上面直接调用一些它从父类(甚至父类的父类Delegate)那里继承来的方法和属性,比较有用的是下面几个:

  • Method
  • Target
  • Combine(),作者想说的或许是定义在Delegate上的静态方法,MulticastDelegate自己有个CombineImpl(Delegate)保护方法。
  • GetInvocationList(),它返回的是一个数组,包括所有的委托对象,按照MSDN的说法,每个对象又都有一个调用列表。
  • Remove()
  • RemoveAll()


另外,委托对象可以调用的方法既包括静态方法,也包括非静态方法,而且在非静态方法的情况下,Target属性就会指向方法所在的对象。


非静态:

定义:

public delegate int BinaryOp(int x, int y);public class SimpleMath{public static int Add(int x, int y) { return x + y; }}

使用:

BinaryOp b = new BinaryOp(SimpleMath.Add);var sum = b(10, 10);


静态:

SimpleMath m = new SimpleMath();BinaryOp b = new BinaryOp(m.Add);

使用GetInvocationList():

static void DisplayDelegateInfo(Delegate delObj){// Print the names of each member in the// delegate's invocation list.foreach (Delegate d in delObj.GetInvocationList()){Console.WriteLine("Method Name: {0}", d.Method);Console.WriteLine("Type Name: {0}", d.Target);}}


通过委托发送消息