c#标准的事件定义与使用

上一篇博文中我写了一篇关于我对事件的理解和使用而那个是为了更好理解事件和认识他,但是一般的使用和.NET库中的事件使用的是标准的事件定义.

标准的 事件定义如下:

public delegate void Mydelegate(object sender,MyEventArgs e);

public event Mydelegate myevent;

委托类型的第一个参数表示的是当前事件发出者的实例对象.

其中第二个参数的类型MyEventArgs是一个继承自EventArgs的类;它主要是事件发出者用来向事件的订阅者传递数据用的.而EventArgs是.NET里面自带的类.

如下是我写的一个完整的 标准事件使用的例子:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{

class PubEventArgs : EventArgs//事件数据类
{
private readonly string m_magazineName;
private readonly DateTime m_pubDate;
public PubEventArgs(string mangazineName,DateTime pubDate)
{
m_magazineName = mangazineName;
m_pubDate = pubDate;

}
public string magazineName
{
get { return m_magazineName; }

}
public DateTime pubDate
{
get
{
return m_pubDate;
}

}

}
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 name, DateTime date)//触发事件方法;
{
Console.WriteLine("发行" + name);
OnPubComputer(new PubEventArgs(name, date));
}
public void issueLife(string name, DateTime date)//触发事件方法;
{
Console.WriteLine("发行" + name);
OnPubLife(new PubEventArgs(name, date));
}

}
class Subscriber//订阅者类;
{

private string name;
public Subscriber(string objname)
{
this.name = objname;
}
public void Receiver(object sender,PubEventArgs e)//订阅者处理方法;
{
Console.WriteLine(this.name+"已订阅" + e.magazineName+" "+e.pubDate);
}

}

class Program
{
static void Main(string[] args)
{
Subscriber sub1 = new Subscriber("fgreen");//订阅者1;
Subscriber sub2 = new Subscriber("ty");//订阅者2;

Publisher pub = new Publisher();//出版社对象;
pub.pubComputer += new Publisher.PubComputerEventHandler(sub1.Receiver);//订阅者1 订阅电脑杂志;
pub.pubLife += new Publisher.PubLifeEventHandler(sub1.Receiver);//订阅者1 订阅生活杂志;

pub.pubLife += new Publisher.PubLifeEventHandler(sub2.Receiver);//订阅者2 订阅生活杂志
//订阅者2并没有订阅电脑杂志;

pub.issueComputer("电脑杂志", Convert.ToDateTime("2015-5-13"));//出版社发行电脑杂志;
pub.issueLife("生活杂志", Convert.ToDateTime("2015-5-13"));//出版社发行生活杂志;
Console.ReadLine();

}
}
}