using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication8
{
class PubEventArgs : EventArgs //创建一个包含事件数据的并继承于EventArgs的PubEventArgs类
{
private readonly string m_magazineName;//创建两个只读属性的变量
private readonly DateTime m_pubData;
public PubEventArgs(string magazineName, DateTime pubData)//创建类的构造函数
{
m_magazineName = magazineName;//通过构造函数给只读变量传入参数
m_pubData = pubData;
}
public string magazineName//为变量magazineName添加属性
{
get { return m_magazineName; }
}
public DateTime pubData
{
get { return m_pubData; }
}
}
class Program
{
class Publisher//出版社
{
public delegate void PubComputerEventHandler(object sender, PubEventArgs e);//
public delegate void PubLifeEventHandler(object sender, PubEventArgs e);
public event PubComputerEventHandler PubComputer;//事件的声明
public event PubLifeEventHandler PubLife;
protected virtual void OnPubComputer(PubEventArgs e)
{
PubComputerEventHandler handler = PubComputer;
if (handler != null)
{
handler(this, e);
}
}
protected virtual void OnPubLife(PubEventArgs e)
{
PubLifeEventHandler handler = PubLife;
if (handler != null)
{
handler(this, e);
}
}
public void issueComputer(string magazineName, DateTime pubData)//触发事件的方法
{
Console.WriteLine("发行" + magazineName);
OnPubComputer(new PubEventArgs(magazineName, pubData));
}
public void issueLife(string magazineName, DateTime pubData)
{
Console.WriteLine("发行" + magazineName);
OnPubLife(new PubEventArgs(magazineName, pubData));
}
}
class Subscriber //订阅者
{
private string name;
public Subscriber(string name)
{
this.name = name;
}
public void Receive(object sender, PubEventArgs e)//在事件订阅者中定义事件处理程序
{
Console.WriteLine(e.pubData + "" + name + "已收到" + e.magazineName);
}
}
static void Main(string[] args)
{
Publisher Pub = new Publisher();
Subscriber zs = new Subscriber("张三");
Pub.PubComputer += new Publisher.PubComputerEventHandler(zs.Receive);//向事件发行者订阅
Subscriber ls = new Subscriber("李四");
Pub.PubComputer+=new Publisher.PubComputerEventHandler(ls.Receive);
Pub.PubLife += new Publisher.PubLifeEventHandler(ls.Receive);
Pub.issueComputer("电脑杂志", Convert.ToDateTime("2015-1-1"));
Pub.issueLife("生活杂志", Convert.ToDateTime("2015-1-1"));
Console.WriteLine();
Console.WriteLine("一年以后");
Pub.PubComputer -= new Publisher.PubComputerEventHandler(ls.Receive);
Pub.issueComputer("电脑杂志", Convert.ToDateTime("2016-1-1"));
Pub.issueLife("生活杂志", Convert.ToDateTime("2016-1-1"));
Console.ReadLine();
}
}
}
C# 事件
最新推荐文章于 2024-04-23 19:57:46 发布