委托实例:
下面的程序执行后输出为:张三吃西瓜,李四吃竹笋,张三吃傻鸟1,李四吃傻鸟1,座谈会结束。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace shijian
{
class Program
{
static void eattoghter(string food, params mydelegate[] values)//定义一个可变数组
{
if (values == null)
{
Console.WriteLine("座谈会结束");
}
else
{
mydelegate eatall = null;
foreach (mydelegate ac in values)
{
eatall += ac;//通过遍历添加方法
}
eatall(food);//传入函数值
}
}
delegate void mydelegate(string food);
static void Main(string[] args)
{
man zs = new man("张三");
man ls = new man("李四");
mydelegate zsd = new mydelegate(zs.eat);
mydelegate lsd = new mydelegate(ls.eat);
zsd("西瓜");
lsd("竹笋");
eattoghter("傻鸟1",lsd,zsd);
eattoghter(null,null);
}
}
public class man
{ private string name;
public man (string name)
{
this.name = name;
}
public void eat(string food)
{
Console.WriteLine(name +"吃"+ food);
}
}
}
简单的事件举例:
以下程序输出:出版社已经发行了刊物,用户已经收。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace shijian2
{
class Program
{
static void Main(string[] args)
{
publisher syf = new publisher();//新建一个实例
subscriber fkwebs = new subscriber();
syf.onpublish += new publisher.mydelegate(fkwebs.recive);
//发行者的的发行事件 pub类下的myaelegete实现委托(订阅者的行为)
syf.issue();//调用执行事件
}
}
class publisher//出版社类
{
public delegate void mydelegate();
public event mydelegate onpublish;
public void issue()
{
if (onpublish != null)//如果事件不为空执行
{
Console.WriteLine("出版社已经发行了刊物");
onpublish();//执行事件
}
}
}
class subscriber//订阅者类
{
public void recive()
{
Console.WriteLine("用户已经收到");
}
}
}
