委托(delegate):
委托声明定义了一种类型,它用一组特定的参数以及返回类型来封装方法。对于静态方法,委托对象封装要调用的方法。对于实例方法,委托对象同时封装一个实例和该实例上的一个方法。如果您有一个委托对象和一组适当的参数,则可以用这些参数调用该委托。
下面看一段代码:
using System ;
delegate void EatDelegate(string food);
class MyDelegate
{
static void zsEat(string food)
{
Console .WriteLine ("张三吃"+food);
}
static void lsEat(string food)
{
Console .WriteLine ("李四吃"+food);
}
static void wwEat(string food)
{
Console .WriteLine ("王五吃"+food);
}
static void Main()
{
EatDelegate zs=new EatDelegate (zsEat ); //C#2.0语法:
EatDelegate zs=zsEat ;
EatDelegate ls=new EatDelegate (lsEat );
EatDelegate ww=new EatDelegate (wwEat );
EatDelegate eatChain=null;
Console .WriteLine ("座谈会开始");
eatChain = zs+ls+ww;
eatChain ("西瓜");
Console .WriteLine ("李四出去接电话");
eatChain -=ls;
eatChain ("香蕉");
Console .WriteLine ("李四回来了");
eatChain +=ls;
eatChain ("桔子");
//下面是匿名方法¨
eatChain += delegate(string food) {Console .WriteLine ("我吃"+food); };
eatChain += delegate(string food) {Console .WriteLine ("你吃"+food); };
eatChain += delegate(string food) {Console .WriteLine ("他吃"+food); };
eatChain ("饭");
}
}
下面是实例方法的一段代码:
using System ;
delegate void EatDelegate(string food);
class Man
{
private string name;
public Man(string name)
{
this .name =name ;
}
public void eat(string food)
{
Console .WriteLine (name+"吃"+food);
}
}
class Party
{
static void Main()
{
Man ZS=new Man ("张三");
Man LS=new Man ("李四");
Man WW=new Man ("王五");
EatDelegate zs=new EatDelegate (ZS.eat );
EatDelegate ls=new EatDelegate (LS.eat );
EatDelegate ww=new EatDelegate (WW.eat );
EatDelegate eatChain=null;
Console .WriteLine ("座谈会开始");
eatChain = zs+ls+ww;
eatChain ("西瓜");
Console .WriteLine ("李四出去接电话");
eatChain -=ls;
eatChain ("香蕉");
Console .WriteLine ("李四回来了");
eatChain +=ls;
eatChain ("桔子");
}
}
委托可作为方法的参数进行动态调用,看下面代码:
using System ;
delegate void EatDelegate(string food);
class Man
{
private string name;
public Man(string name)
{
this .name =name ;
}
public void eat(string food)
{
Console .WriteLine (name+"吃"+food);
}
}
class Party
{
static void eatTogether(string food,params EatDelegate [] values)
{
if (values ==null )
{
Console .WriteLine ("座谈会结束");
}
else
{
EatDelegate eatChain=null ;
foreach (EatDelegate ed in values )
eatChain +=ed;
eatChain (food);
Console .WriteLine ();
}
}
static void Main()
{
Man ZS=new Man ("张三");
Man LS=new Man ("李四");
Man WW=new Man ("王五");
EatDelegate zs=new EatDelegate (ZS.eat );
EatDelegate ls=new EatDelegate (LS.eat );
EatDelegate ww=new EatDelegate (WW.eat );
Console .WriteLine ("座谈会开始");
eatTogether("西瓜",zs,ls,ww);
Console .WriteLine ("李四出去接电话");
eatTogether("香蕉",zs,ww);
Console .WriteLine ("李四回来了");
eatTogether("桔子",zs,ls,ww);
Console .WriteLine ("座谈会结束");
eatTogether (null ,null );
}
}