【delegate】
delegate定义了一个函数引用类型,犹如C++中的typedef,也犹如Objc中的Block(在捕获变量上有点差异)。
1、有名方法,delegate捕获的方法可以是实例方法或静态方法。
1 // Declare a delegate 2 delegate void Del(); 3 4 class SampleClass 5 { 6 public void InstanceMethod() 7 { 8 System.Console.WriteLine("A message from the instance method."); 9 } 10 11 static public void StaticMethod() 12 { 13 System.Console.WriteLine("A message from the static method."); 14 } 15 } 16 17 class TestSampleClass 18 { 19 static void Main() 20 { 21 SampleClass sc = new SampleClass(); 22 23 // Map the delegate to the instance method: 24 Del d = sc.InstanceMethod; 25 d(); 26 27 // Map to the static method: 28 d = SampleClass.StaticMethod; 29 d(); 30 } 31 } 32 /* Output: 33 A message from the instance method. 34 A message from the static method. 35 */
2、匿名方法。
也可以不创建delegate对象:
对于捕获,编译器会创建额外的类来容纳变量,而之前定义该变量的类的实例拥有该变量的引用,捕获到该变量的匿名方法同样也拥有该变量的引用。所以,方法内的变量并不是我们想象中存储在方法对应的栈帧中。我们知道,所有引用都是在拥有该引用的实例的堆上,除非委托被回收,否则该引用就不会被销毁。
【合并委托】
可以将多个委托对象相加得到一个单一个组合委托对象(合并委托)。
using System; // Define a custom delegate that has a string parameter and returns void. delegate void CustomDel(string s); class TestClass { // Define two methods that have the same signature as CustomDel. static void Hello(string s) { System.Console.WriteLine(" Hello, {0}!", s); } static void Goodbye(string s) { System.Console.WriteLine(" Goodbye, {0}!", s); } static void Main() { // Declare instances of the custom delegate. CustomDel hiDel, byeDel, multiDel, multiMinusHiDel; // In this example, you can omit the custom delegate if you // want to and use Action<string> instead. //Action<string> hiDel, byeDel, multiDel, multiMinusHiDel; // Create the delegate object hiDel that references the // method Hello. hiDel = Hello; // Create the delegate object byeDel that references the // method Goodbye. byeDel = Goodbye; // The two delegates, hiDel and byeDel, are combined to // form multiDel. multiDel = hiDel + byeDel; // Remove hiDel from the multicast delegate, leaving byeDel, // which calls only the method Goodbye. multiMinusHiDel = multiDel - hiDel; Console.WriteLine("Invoking delegate hiDel:"); hiDel("A"); Console.WriteLine("Invoking delegate byeDel:"); byeDel("B"); Console.WriteLine("Invoking delegate multiDel:"); multiDel("C"); Console.WriteLine("Invoking delegate multiMinusHiDel:"); multiMinusHiDel("D"); } } /* Output: Invoking delegate hiDel: Hello, A! Invoking delegate byeDel: Goodbye, B! Invoking delegate multiDel: Hello, C! Goodbye, C! Invoking delegate multiMinusHiDel: Goodbye, D! */
参考:
1、http://msdn.microsoft.com/zh-cn/library/98dc08ac(v=vs.90).aspx
2、http://msdn.microsoft.com/zh-cn/library/0yw3tz5k(v=vs.90).aspx
3、http://www.cnblogs.com/wenjiang/archive/2013/03/12/2954913.html