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

转载于:https://www.cnblogs.com/mt4us/archive/2011/04/29/2032398.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值