C#中事件是一种特殊的委托
class Publisher //出版社
{
public delegate void Publish();//声明事件所需的代理
public event Publish OnPublish;//事件的声明
public void issue()//触发事件
{
if (OnPublish != null)
{
Console.WriteLine("发行刊物");
OnPublish();
}
}
}
class Subscriber//订阅者
{
public void Receive()//在事件订阅者中定义事件处理程序
{
Console.WriteLine("订阅者已经收到刊物");
}
}
class Story
{
static void Main()
{
Publisher Pub = new Publisher();
Subscriber zs = new Subscriber();
Pub.OnPublish+=new Publisher.Publish(zs.Receive);//向事件发行者订阅一个事件
Pub.issue();//触发事件
}
}
例子二:
class Publisher//出版社
{
public delegate void PubComputer(string magazineName);//声明事件所需的代理
public delegate void PubLift(string magazineName);
public event PubComputer OnPubComputer;//事件的声明
public event PubLift OnPubLife;
public void issueComputer()//触发事件的方法
{
if (OnPubComputer != null)
{
Console.WriteLine("发行电脑杂志");
OnPubComputer("电脑杂志");
}
}
public void issueLife()
{
if (OnPubLife != null)
{
Console.WriteLine("发行生活杂志");
OnPubLife("生活杂志");
}
}
}
class Subscriber//订阅者
{
private string name;
public Subscriber(string name)
{
this.name = name;
}
public void Receive(string magazineName)//在事件订阅者中定义事件处理程序
{
Console.WriteLine(name + "已经收到" + magazineName);
}
}
class Story
{
static void Main()
{
Publisher Pub = new Publisher();
Subscriber zs = new Subscriber("张三");
Pub.OnPubComputer+=new Publisher.PubComputer(zs.Receive);//向事件发行者订阅一个事件
Subscriber ls = new Subscriber("李四");
Pub.OnPubComputer += new Publisher.PubLift(ls.Receive);
Pub.OnPubLife+=new Publisher.PubLift(ls.Receive);
Pub.issueComputer();//触发事件
Pub.issueLife();
Console.WriteLine();
Console.WriteLine("一年后");
Pub.OnPubComputer -= new Publisher.PubComputer(ls.Receive);
Pub.issueComputer();
Pub.issueLife();
}
}