using System;
class Publisher
{
public delegate void PubComputer(string magazineName);
public delegate void PubLife(string magazineName);
public event PubComputer OnPubComputer;
public event PubLife 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.PubComputer(ls.Receive);
pub.OnPubLife+=new Publisher.PubLife(ls.Receive);
pub.issueComputer();
pub.issueLife();
Console.WriteLine();
Console.WriteLine("一年后");
pub.OnPubComputer-=new Publisher.PubComputer(ls.Receive);
pub.issueComputer();
pub.issueLife();
}
}