委托
来源:互联网 发布:天谕小茗同学数据 编辑:程序博客网 时间:2024/04/29 08:51
委托(delegate)是一种可以把引用储存为函数的类型。
委托是一种引用方法的类型。一旦为委托分配了方法,委托将与该方法具有完全相同的行为。委托方法的使用可以像其他任何方法一样,具有参数和返回值
public delegate int PerformCalculation(int x, int y);
delegate void detegateEat(string food);
class Method
{
public static void zsEat(string food)
{
Console.WriteLine("张三吃" + food);
}
public static void lsEat(string food)
{
Console.WriteLine("李四吃" + food);
}
public static void wwEat(string food)
{
Console.WriteLine("王五吃" + food);
}
static void Main()
{
detegateEat zs = new detegateEat(zsEat);
detegateEat ls = new detegateEat(lsEat);
detegateEat ww = new detegateEat(wwEat);
zs("西瓜");
ls("西瓜");
ww("西瓜");//这里似乎有点烦哦。。
Console.ReadLine();
}
}
class Method
{
public static void zsEat(string food)
{
Console.WriteLine("张三吃" + food);
}
public static void lsEat(string food)
{
Console.WriteLine("李四吃" + food);
}
public static void wwEat(string food)
{
Console.WriteLine("王五吃" + food);
}
static void Main()
{
detegateEat zs = new detegateEat(zsEat);
detegateEat ls = new detegateEat(lsEat);
detegateEat ww = new detegateEat(wwEat);
zs("西瓜");
ls("西瓜");
ww("西瓜");//这里似乎有点烦哦。。
Console.ReadLine();
}
}
static void Main()
{
detegateEat zs = new detegateEat(zsEat);
detegateEat ls = new detegateEat(lsEat);
detegateEat ww = new detegateEat(wwEat);
zs("西瓜");
ls("西瓜");
ww("西瓜");//这里似乎有点烦哦。。
//下面定义一个委托链;
detegateEat eat;
eat = zs + ls + ww;
eat("番茄");
//委托链还可以加减;
eat -= ls;
eat("香蕉");
Console.ReadLine();
}
{
detegateEat zs = new detegateEat(zsEat);
detegateEat ls = new detegateEat(lsEat);
detegateEat ww = new detegateEat(wwEat);
zs("西瓜");
ls("西瓜");
ww("西瓜");//这里似乎有点烦哦。。
//下面定义一个委托链;
detegateEat eat;
eat = zs + ls + ww;
eat("番茄");
//委托链还可以加减;
eat -= ls;
eat("香蕉");
Console.ReadLine();
}
上面委托代理的是一个静态的方法,下面我们来看如何代理一个动态的方法。
delegate void detegateEat(string food);
class Man
{
private string name;
//构造函数。
public Man (string name)
{
this .name =name ;
}
public void eat(string food)
{
Console .WriteLine (name +"吃"+food );
}
}
class part
{
static void Main()
{
Man ZS = new Man("张三");
Man LS= new Man("李四");
Man WW = new Man("王五");
detegateEat zs = new detegateEat(ZS .eat );
detegateEat ls = new detegateEat(LS .eat );
detegateEat ww = new detegateEat(WW.eat );
zs("西瓜");
ls("西瓜");
ww("西瓜");//这里似乎有点烦哦。。
//下面定义一个委托链;
detegateEat eat;
eat = zs + ls + ww;
eat("番茄");
//委托链还可以加减;
eat -= ls;
eat("香蕉");
Console.ReadLine();
}
}
class Man
{
private string name;
//构造函数。
public Man (string name)
{
this .name =name ;
}
public void eat(string food)
{
Console .WriteLine (name +"吃"+food );
}
}
class part
{
static void Main()
{
Man ZS = new Man("张三");
Man LS= new Man("李四");
Man WW = new Man("王五");
detegateEat zs = new detegateEat(ZS .eat );
detegateEat ls = new detegateEat(LS .eat );
detegateEat ww = new detegateEat(WW.eat );
zs("西瓜");
ls("西瓜");
ww("西瓜");//这里似乎有点烦哦。。
//下面定义一个委托链;
detegateEat eat;
eat = zs + ls + ww;
eat("番茄");
//委托链还可以加减;
eat -= ls;
eat("香蕉");
Console.ReadLine();
}
}