委托(Delegate)

来源:互联网 发布:windows系统哪个开机快 编辑:程序博客网 时间:2024/06/05 14:45

委声明定义了一种类型,它用一组特定的参数以及类型来封装方法。对于静态方法,委托对象封装要调用的方法,对于实例方法,委托对象同时封装一个实例和该实例上的一个方法。如果您有一个委托对象和一组适当的参数,则可以用这些参数调用该方法。



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 委托1
{
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(string[] args)
//{
// EatDelegate zs = new EatDelegate(zsEat);
// EatDelegate ls = new EatDelegate(lsEat);
// EatDelegate ww = new EatDelegate(wwEat);
// zsEat("西瓜");
// lsEat("西瓜");
// wwEat("西瓜");
// EatDelegate EatChain = null;
// EatChain = zs + ls + ww;
// Console.WriteLine("张三,李四,王五一起开Party!");
// EatChain("西瓜");
// Console.WriteLine("张三出去接电话!");
// EatChain -= zs;
// EatChain("桔子");
// Console.WriteLine("张三回来了!");
// EatChain += zs;
// EatChain("香蕉");
//}
//以下为带匿名方法的委托形成原理代码
static void Main(string[] args)
{
EatDelegate EatChain=null;
EatChain += delegate(string food) { Console.WriteLine("张三吃" + food); };//带匿名方法的委托,c#2.0版本开始出现
EatChain += delegate(string food) { Console.WriteLine("李四吃" + food); };//带匿名方法的委托,c#2.0版本开始出现
EatChain += delegate(string food) { Console.WriteLine("王五吃" + food); };//带匿名方法的委托,c#2.0版本开始出现
EatChain("西瓜");
}
}
}

0 0
原创粉丝点击