Event学习(二)

/*事件是类在发生其关注的事件时用来提供通知的一种方式
 *
 */
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();
  }
 }
}
以下图片是结果 

执行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值