/*事件是类在发生其关注的事件时用来提供通知的一种方式
*
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace Event
{
//派生這個類主要用于傳遞參數和規范寫法!
class PubEventArgs:EventArgs
{
private readonly string _MagazineName; //赋值后就不能修改值
private readonly DateTime _PubDate;
public PubEventArgs(string AMagazineName,DateTime APubDate)
{
_MagazineName = AMagazineName;
_PubDate = APubDate;
}
public string MagazineName
{
get { return _MagazineName;}
}
public DateTime PubDate
{
get { return _PubDate;}
}
}
//注意不能把他表示为公共类
class Publisher //出版社
{
public delegate void PubComputerEventHandler(object sender, PubEventArgs e );//声明事件代理名称是事件名称+EventHandler
//PubEventArgs为参数
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 AMagazineName,DateTime APubdate) //触发事件
{
Console.WriteLine("發行"+AMagazineName);
OnPubComputer(new PubEventArgs(AMagazineName,APubdate));
}
public void IssueLife(string AMagazineName, DateTime APubdate)
{
Console.WriteLine("發行"+AMagazineName);
OnPubLife(new PubEventArgs(AMagazineName,APubdate));
}
}
class Subscriber //订阅者
{
private string _Name;
public Subscriber(string AName)
{
this._Name = AName;
}
//以下方法的參數和返回值必須和OnPubComputer代理一樣
public void Receive(object sender, PubEventArgs e)
{
Console.WriteLine(e.PubDate + " " + _Name + "已經收到" + e.MagazineName);
}
}
public class Story
{
static void Main()
{
Publisher Pub = new Publisher();
Subscriber Sub = new Subscriber("張三");
//實際上是事件實現動態加載方法
Pub.PubComputer += new Publisher.PubComputerEventHandler(Sub.Receive);
Subscriber Sub1 = new Subscriber("李四");
Pub.PubLife += new Publisher.PubLifeEventHandler(Sub1.Receive);
Pub.IssueComputer("電腦雜志",Convert.ToDateTime("2007/01/01")); //触发事件
Pub.IssueLife("生活雜志", Convert.ToDateTime("2007/01/01"));
Pub.PubLife -= new Publisher.PubLifeEventHandler(Sub1.Receive);
Pub.IssueComputer("電腦雜志", Convert.ToDateTime("2008/01/01")); //触发事件
Pub.IssueLife("生活雜志", Convert.ToDateTime("2008/01/01"));
Console.ReadLine();
}
}
}
以下图片是结果