C# 中的delegate

刚开始,见了多次,但是从来没有理解,一大早过来就先google一下,先把这个问题搞清楚。

delegate 的字面意思
vt. 委派…为代表
n. 代表

msdn上的解释
A delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature. A delegate instance encapsulates a static or an instance method. Delegates are roughly similar to function pointers in C++; however, delegates are type-safe and secure.

delegate声明一种引用类型,用来封装有特定签名的方法,可以是一个静态的方法或是实例的方法。类似于C++中的方法指针。

声明格式

[attributes] [modifiers] delegate result-type identifier ([formal-parameters]);
范例一
// keyword_delegate.cs
// delegate declaration
delegate void MyDelegate(int i);

class Program
{
   public static void Main()
   {
      TakesADelegate(new MyDelegate(DelegateFunction));
   }

   public static void TakesADelegate(MyDelegate SomeFunction)
   {
      SomeFunction(21);
   }
   
   public static void DelegateFunction(int i)
   {
      System.Console.WriteLine("Called by delegate with number: {0}.", i);
   }
}
范例二
1 // keyword_delegate2.cs
2 // Calling both static and instance methods from delegates
3 using System;
4
5 // delegate declaration
6 delegate void MyDelegate();
7
8 public class MyClass
9 {
10 public void InstanceMethod()
11 {
12 Console.WriteLine("A message from the instance method.");
13 }
14
15 static public void StaticMethod()
16 {
17 Console.WriteLine("A message from the static method.");
18 }
19 }
20
21 public class MainClass
22 {
23 static public void Main()
24 {
25 MyClass p = new MyClass();
26
27 // Map the delegate to the instance method:
28 MyDelegate d = new MyDelegate(p.InstanceMethod);
29 d();
30
31 // Map to the static method:
32 d = new MyDelegate(MyClass.StaticMethod);
33 d();
34 }
35 }
本文中的大部分内容摘自http://msdn.microsoft.com/zh-cn/library/900fyy8e%28v=VS.71%29.aspx

posted on 2011-04-29 09:05  Sam Lau  阅读(344)  评论(0编辑  收藏  举报

导航