在项目中用事件消息有许多好处,比如解耦合,结构清晰,一条消息对应多个事件等等…
事件码用枚举来区分。事件类型用委托定义。
没有参数:
添加事件监听代码:
public static void AddListener(EventType type,CallBack callback)
{
if (!m_EventControl.ContainsKey(type))
{
m_EventControl.Add(type, null);
}
Delegate d = m_EventControl[type];
if (d != null && d.GetType() !=callback.GetType())
{
throw new Exception("添加事件类型参数不符");
}
//关联事件
m_EventControl[type] =(CallBack)m_EventControl[type] + callback;
}
移除事件监听:
public static void RemoveListener(EventType type,CallBack callback)
{
if (m_EventControl.ContainsKey(type))
{
Delegate d = m_EventControl[type];
if (d == null || d.GetType() != callback.GetType())
{
throw new Exception("移除监听错误:委托事件为空(Value) 或者 移除委托的类型不一样");
}
}
else
{
throw new Exception("移除监听错误:不存在事件码(Key)");
}
m_EventControl[type] = (CallBack)m_EventControl[type] - callback;
}
一个参数:
事件监听的写法:
public static void AddListener<T>(EventType type, CallBack<T> callback)
{
if (!m_EventControl.ContainsKey(type))
{
m_EventControl.Add(type, null);
}
Delegate d = m_EventControl[type];
if (d != null && d.GetType() != callback.GetType())
{
throw new Exception("添加事件类型参数不符");
}
//关联事件
m_EventControl[type] = (CallBack<T>)m_EventControl[type] + callback;
}
移除事件监听的方法:
public static void RemoveListener<T>(EventType type, CallBack<T> callback)
{
if (m_EventControl.ContainsKey(type))
{
Delegate d = m_EventControl[type];
if (d == null || d.GetType() != callback.GetType())
{
throw new Exception("移除监听错误:委托事件为空(Value) 或者 移除委托的类型不一样");
}
}
else
{
throw new Exception("移除监听错误:不存在事件码(Key)");
}
m_EventControl[type] = (CallBack<T>)m_EventControl[type] - callback;
}