1.源码
代码如下(示例):
using System;
using System.Collections.Generic;
/// <summary>
/// 简单的事件系统
/// </summary>
public class EventSystemSimple
{
public delegate void Handler(object obj);
private static Dictionary<string, Handler> _Events = new Dictionary<string, Handler>();
public static void Register(string key, Handler handler)
{
Handler h = null;
if (_Events.TryGetValue(key, out h))
{
h += handler;
}
else
{
_Events.Add(key, handler);
}
}
public static void UnRegister(string key, Handler handler)
{
Handler h = null;
if (_Events.TryGetValue(key, out h))
{
h -= handler;
if (h == null)
{
_Events.Remove(key);
}
}
}
public static void Broadcast(string key, object obj)
{
Handler h = null;
if (_Events.TryGetValue(key, out h))
{
h(obj);
}
}
}
/// <summary>
/// 基于模板的事件系统
/// </summary>
public class EventSystemT
{
// 定义代理类
public delegate void Handler();
public delegate void Handler<T>(T arg);
public delegate void Handler<T, X>(T arg1, X arg2);
// 事件集合
private static Dictionary<string, Delegate> _Events = new Dictionary<string, Delegate>();
// 1个参数
public static void Register(string key, Handler handler)
{
Delegate h = null;
if (_Events.TryGetValue(key, out h))
{
if (h.GetType() == handler.GetType())
{
h = (Handler)h + handler;
}
else
{
throw new Exception(string.Format("添加监听错误:事件{0}的委托类型{1}与添加的委托类型{2}不同!", key, h.GetType(), handler.