浅析C#中的委托

浅析C#中的委托:
首先通过一个例子来阐述delegate的用法。
 1using System; 
 2class MyDelegate 
 3
 4static void chEat(string food) 
 5
 6Console.WriteLine("葱花吃"+food); 
 7}
 
 8static void Main() 
 9
10chEat("西瓜"); 
11}
 
12}
 
13
下面声明一个delegate实例,然后调用。
 1using System; 
 2delegate void EatDelegate(string food);//此处签名应该与chEat方法签名保持一致 
 3class MyDelegate 
 4
 5static void chEat(string food) 
 6
 7Console.WriteLine("葱花吃"+food); 
 8}
 
 9static void Main() 
10
11EatDelegate ch=new EatDelegate(chEat); 
12ch("西瓜"); 
13}
 
14}
 
15

输出结果是:
葱花吃西瓜
样样吃西瓜
大蒜吃西瓜
但是:声明三次方法过于麻烦,用"委托链"解决。代码如下:
 1using System; 
 2delegate void EatDelegate(string food); 
 3class MyDelegate 
 4
 5static void chEat(string food) 
 6
 7Console.WriteLine("葱花吃"+food); 
 8}
 
 9static void yyEat(string food) 
10
11Console.WriteLine("样样吃"+food); 
12}
 
13static void dsEat(string food) 
14
15Console.WriteLine("大蒜吃"+food); 
16}
 
17static void Main() 
18
19EatDelegate ch=new EatDelegate(chEat); 
20EatDelegate yy=new EatDelegate(yyEat); 
21EatDelegate ds=new EatDelegate(dsEat); 
22EatDelegate EatChain; //使用委托链解决 
23eatChain=ch+yy+ds; 
24eatChain("西瓜"); 
25}
 
26}
 
27
为了让程序富有逻辑性,同时为了说明C#2.0的匿名方法,请看如下代码:
 1using System; 
 2delegate void EatDelegate(string food); 
 3class MyDelegate 
 4
 5static void chEat(string food) 
 6
 7Console.WriteLine("葱花吃"+food); 
 8}
 
 9static void yyEat(string food) 
10
11Console.WriteLine("样样吃"+food); 
12}
 
13static void dsEat(string food) 
14
15Console.WriteLine("大蒜吃"+food); 
16}
 
17static void Main() 
18
19EatDelegate ch=new EatDelegate(chEat); 
20EatDelegate yy=new EatDelegate(yyEat); 
21EatDelegate ds=new EatDelegate(dsEat); 
22EatDelegate eatChain; 
23Console.WriteLine("葱花,样样,大蒜在聊天"); 
24eatChain=ch+yy+ds; 
25eatChain("西瓜"); 
26Console.WriteLine("葱花出去接她男朋友的电话"); 
27eatChain-=ch; //C sharp重载了-= += 
28eatChain("葡萄"); 
29Console.WriteLine("葱花约会回来了"); 
30eatChain+=ch; 
31eatChain("芒果"); 
32}
 
33}
 
34
请注意:上面chEat(),yyEat(),dsEat()过于繁琐,可以用C# 2.0匿名方法解决:
 1using System; 
 2delegate void EatDelegate(string food); 
 3class MyDelegate 
 4
 5static void Main() 
 6
 7EatDelegate eatChain=null
 8eatChain+=delegate(string food){Console.WriteLine("葱花吃"+food);}
 9eatChain+=delegate(string food){Console.WriteLine("样样吃"+food);}
10eatChain+=delegate(string food){Console.WriteLine("大蒜吃"+food);}
11eatChain("西瓜"); 
12}
 
13}
 
14
输出结果:
葱花吃西瓜
样样吃西瓜
大蒜吃西瓜
由此可以得出委托的特点:
(1)委托是类型安全的。
(2)委托允许将方法作为参数传递。
(3)委托可以定位回调方法。
(4)委托可以定义委托链。

posted on 2008-03-24 11:56  CodeShark  阅读(253)  评论(1编辑  收藏  举报

导航