C#中事件机制是比较难理解的,但它又是很有效的一种体系结构,跟Windows基于消息的架构是类似的,我比较了一下,应该是同出一辙。
C#中事件机制是通过delegate委托很Event实现的。
简单介绍Delegate 和Event:
Delegate类实际上相当于函数指针,但比函数指针安全。委托声明定义了一个从System.Delegate类派生的类,委托实例封装一个调用列表,
此列表列出一个或多个方法,每个方法均作为一个可调用的实例来应用。
如 public delegate void Function(int i);//一个返回值是void ,参数是int的函数的委托实例。
事件Event为类及类的实例提供向外界发送通知的能力
下面是一个自己写得代码:定义了一个Event类,继承与EventArgs类,用于在触发事件时携带一些自定义的信息
定义一个Publisher发布者类
定义了两个Subscribler订阅者类A B
主类 Program
Event类:
class Event:EventArgs
{
public int type;
public string info;
public string PrintInfo()
{
return "事件类型是:"+type.ToString()+" "+"事件内容是:"+info;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Publisher发布者类:
public delegate void ChangedEventHandler(object sender,Event e);//定义的一个处理发布者事件的委托类
class Publisher//发布者类
{
public event ChangedEventHandler Changed;//绑定事件和处理它的委托类
private Event e;//触发事件时包含的事件内容
protected virtual void OnChanged()//触发事件的类
{
if (Changed != null)//如果事件没有触发,就触发
{
Changed(this, e);
}
}
public void SetEvent(Event e)//当设置事件时就触发它
{
this.e = e;
OnChanged();//触发事件
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
两个Subscribler订阅者类A B:
class SubscriberA//订阅者A
{
private Publisher publisher=new Publisher();//申明一个发布者对象,这样才能使用它(注册它)
public SubscriberA(Publisher p)//注册发布者
{
publisher = p;
publisher.Changed += new ChangedEventHandler(ResponserPublisher);//对发布者发布的事件进行处理绑定
}
public void ResponserPublisher(object sender,Event e)//对事件进行处理的函数
{
//只处理事件类型是1的事件
if(e.type==1)
{
Console.WriteLine("我是订阅者A,我只关注事件类型是1的事件,我现在收到的是:");
Console.WriteLine(e.PrintInfo());
}
}
}
class SubscriberB//订阅者B
{
private Publisher publisher=new Publisher();//申明一个发布者对象,这样才能使用它(注册它)
public SubscriberB(Publisher p)//注册发布者
{
publisher = p;
publisher.Changed += new ChangedEventHandler(ResponserPublisher);//对发布者发布的事件进行处理绑定
}
public void ResponserPublisher(object sender,Event e)//对事件进行处理的函数
{
//只处理事件类型是2的事件
if(e.type==2)
{
Console.WriteLine("我是订阅者B,我只关注事件类型是2的事件,我现在收到的是:");
Console.WriteLine(e.PrintInfo());
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
主类 Program:
class Program
{
static void Main(string[] args)
{
Event A = new Event();
Event B = new Event();
A.type = 1;
A.info = "这是事件A";
B.type = 2;
B.info = "这是事件B";
Publisher publisher = new Publisher();
SubscriberA subscriberA = new SubscriberA(publisher);//注册发布者
SubscriberB subScriberB = new SubscriberB(publisher);//注册发布者
publisher.SetEvent(A);//发布者发布A类事件
Console.WriteLine();
publisher.SetEvent(B);//发布者发布B类事件
Console.Read();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
输出结果为:
我是订阅者A,我只关注事件类型是1的时间,我现在收到的是:
事件类型是:1 事件内容是:这是事件A
我是订阅者B,我只关注事件类型是2的时间,我现在收到的是:
事件类型是:2 事件内容是:这是事件B
浙公网安备 33010602011771号