委托的声明和使用

委托是一种动态函数调用方式,通过委托可以将一些相同类型的函数串联起来依次执行。委托同时是函数回调和事件机制的基础。

委托的定义通过delegate关键字来声明委托,声明委托之后通过new,“+=”,“-=”运算符为其分配函数,这样就可以直接

使用函数一样使用委托来调用分配给它的函数。下面一个例子可以帮助我们更好地理解委托。

 

代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Example2
 7 {
 8     class Program
 9     {
10         delegate void StrParaFunc(int no,string str);//声明一个委托
11 
12         static void PrintString(int no,string str)//Printstring函数定义
13         {
14             System.Console.WriteLine("{0}:PrintString:{1}",no,str);
15         }
16 
17         static void ShowString(int no, string str)//Showstring函数定义
18         {
19             Console.WriteLine("{0}:ShowString:{1}",no,str);
20         }
21 
22         static void Main(string[] args)
23         {
24             //通过new初始化委托
25             StrParaFunc spfHandle1 = new StrParaFunc(PrintString);
26             spfHandle1(1"a string 1");
27             spfHandle1(2"a string 2");
28             spfHandle1 += ShowString;
29             spfHandle1(3"a string3");
30             spfHandle1 -= PrintString;
31             spfHandle1(4"a string4");
32             //通过函数地址直接初始化委托
33             StrParaFunc spfHandle2 = ShowString;
34             spfHandle2(14"我是2的委托哦!");
35             spfHandle2 += PrintString;
36             spfHandle2(11"我是2的委托哦!");
37         }
38     }
39 }
40 

 

 

posted on 2010-03-13 17:11  晴天1848  阅读(317)  评论(0)    收藏  举报