using System;using System.Collections.Generic; namespace CustomUtils{ /// <summary> /// 事件管理器 /// </summary> public class EventManager { private reado ...
using System;
using System.Collections.Generic;
namespace CustomUtils
{
/// <summary>
/// 事件管理器
/// </summary>
public class EventManager
{
private readonly static Dictionary<string, Action<EventMessageArgs>> eventTask = new Dictionary<string, Action<EventMessageArgs>>();
/// <summary>
/// 註冊事件
/// </summary>
/// <param name="eventKey">事件索引</param>
/// <param name="actionValue">事件回調</param>
public static void RegisterEvent(string eventKey, Action<EventMessageArgs> actionValue)
{
if (!eventTask.ContainsKey(eventKey))
{
eventTask[eventKey] = actionValue;
}
else
{
if (eventTask[eventKey] != null)
{
Delegate[] dels = eventTask[eventKey].GetInvocationList();
foreach (Delegate del in dels)
{
if (del.Equals(actionValue))
return;
}
}
eventTask[eventKey] += actionValue;
}
}
/// <summary>
/// 註銷事件
/// </summary>
/// <param name="eventKey">事件索引</param>
/// <param name="actionValue">事件回調</param>
public static void UnregisterEvent(string eventKey, Action<EventMessageArgs> actionValue)
{
if (eventTask.ContainsKey(eventKey))
{
eventTask[eventKey] -= actionValue;
if (eventTask[eventKey] == null)
{
eventTask.Remove(eventKey);
}
}
}
/// <summary>
/// 觸發事件
/// </summary>
/// <param name="eventKey">事件索引</param>
/// <param name="args">消息內容(只在單次觸發有效,若要連續傳遞請使用 CopyMessage )</param>
public static void PostEvent(string eventKey, EventMessageArgs args)
{
if (eventTask.ContainsKey(eventKey))
{
eventTask[eventKey](args);
}
args.Dispose();
}
}
/// <summary>
/// 事件通知數據
/// </summary>
public class EventMessageArgs : IDisposable
{
public EventMessageArgs()
{
messages = new Dictionary<string, object>();
}
private Dictionary<string, object> messages;
/// <summary>
/// 複製
/// </summary>
/// <param name="msg"></param>
public void CopyMessage(EventMessageArgs msg)
{
messages = msg.messages;
}
/// <summary>
/// 新增或替換
/// </summary>
/// <param name="key">索引</param>
/// <param name="value">新數據</param>
public void AddOrReplaceMessage(string key, object value)
{
if (CheckMessage(key))
messages[key] = value;
else
messages.Add(key, value);
}
/// <summary>
/// 刪除
/// </summary>
/// <param name="key">索引</param>
public void RemoveMessage(string key)
{
if (CheckMessage(key))
messages.Remove(key);
}
/// <summary>
/// 獲取內容
/// </summary>
/// <param name="key">索引</param>
/// <returns>引用類型數據</returns>
public object GetMessage(string key)
{
if (CheckMessage(key))
return messages[key];
else
return null;
}
/// <summary>
/// 獲取內容
/// </summary>
/// <typeparam name="T">類型</typeparam>
/// <param name="key">索引</param>
/// <returns>數據</returns>
public T GetMessage<T>(string key)
{
if (CheckMessage(key))
return (T)messages[key];
else
return default(T);
}
/// <summary>
/// 釋放
/// </summary>
public void Dispose()
{
messages.Clear();
messages = null;
}
private bool CheckMessage(string key)
{
return messages.ContainsKey(key);
}
}
}