簡單的事件系統c#
阿新 • • 發佈:2018-12-21
簡單的事件系統:可以通過操作碼來執行相關的函式操作,還可以通過分模組,再新增一個模組碼,進一步細分事件系統
using System.Collections.Generic;
using System;
/// <summary>
/// 簡單的事件系統
/// </summary>
public class EventMgr
{
private static EventMgr m_instance;
public static EventMgr Instance
{
get
{
if (m_instance == null)
{
m_instance = new EventMgr();
}
return m_instance;
}
}
private EventMgr() { }
private Dictionary<CMD, List<System.Action<object[]>>> map = new Dictionary<CMD, List<Action<object[]>>> ();
public void Add(CMD key, Action<object[]> func)
{
if (!map.ContainsKey(key))
{
List<System.Action<object[]>> list = new List<Action<object[]>>();
map.Add(key, list);
}
map[key].Add(func);
}
public void Remove(CMD key, Action<object[]> func)
{
if (map.ContainsKey(key))
{
if (map[key].Contains(func))
{
map[key].Remove(func);
if (map[key].Count == 0)
{
map[key].Clear();
map.Clear();
}
}
}
}
/// <summary>
/// 觸發訊息
/// </summary>
/// <param name="key">事件碼</param>
/// <param name="data">引數</param>
public void Trigger(CMD key, params object[] data)
{
if (map.ContainsKey(key))
{
int l = map[key].Count;
for (int i = 0; i < l; i++)
{
map[key][i](data);
}
}
}
}
public enum CMD
{
Add_Equip,
Remove_Equip
}