2025-01-02 12:15:45 +08:00

128 lines
4.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace CG.Framework
{
/// <summary>
/// 事件系统
/// </summary>
public class EventManager : IEventManager
{
//容器
public Dictionary<Type, EventHandler> delegates;
public Dictionary<Delegate, EventHandler> delegatesLookup;
public EventManager()
{
this.delegates = new Dictionary<Type, EventHandler>();
this.delegatesLookup = new Dictionary<Delegate, EventHandler>();
}
public void AddListener<T>(EventHandler<T> del) where T : IGameEvent
{
if (!delegatesLookup.ContainsKey(del))
{
EventHandler eventHandler = delegate (IGameEvent e)
{
del((T)e);
};
delegatesLookup[del] = eventHandler;
if (delegates.TryGetValue(typeof(T), out var value))
{
value = (delegates[typeof(T)] = (EventHandler)Delegate.Combine(value, eventHandler));
}
else
{
delegates[typeof(T)] = eventHandler;
}
}
}
public void Clear()
{
delegates.Clear();
delegatesLookup.Clear();
}
public void Raise(IGameEvent e)
{
EventHandler eventHandler;
if (delegates.TryGetValue(e.GetType(), out eventHandler))
{
Delegate[] delegates_array = eventHandler.GetInvocationList();
int length = delegates_array.Length;
WDebug.Log("[EventManager.Raise]注册的事件集合长度" + ((int)length));
for (int i = 0; i < length; i++)
{
Delegate delegate2 = delegates_array[i];
try
{
if (delegate2 != null) delegate2.DynamicInvoke(e);
}
catch (System.Exception ex)
{
string msg = ex.ToString();
string stack_trace = ex.StackTrace;
if (ex.InnerException != null)
{
msg = ex.InnerException.Message;
stack_trace = ex.InnerException.StackTrace;
}
Debug.Log("[GameEventManager]Raise: {0}\nStack Trace: {1}\n因为出现了这个异常该事件监听器将被移除" + msg + stack_trace);
var evt_type = e.GetType();
var item_evt_handler = delegate2 as EventHandler;
if (item_evt_handler != null) eventHandler -= item_evt_handler;
if (eventHandler == null)
{
delegates.Remove(evt_type);
}
else
delegates[evt_type] = eventHandler;
var etor = delegatesLookup.GetEnumerator();
while (etor.MoveNext())
{
if (etor.Current.Value == item_evt_handler)
{
delegatesLookup.Remove(etor.Current.Key);
break;
}
}
}
}
}
}
public void RemoveListener<T>(EventHandler<T> del) where T : IGameEvent
{
if (!delegatesLookup.TryGetValue(del, out var value))
{
return;
}
if (delegates.TryGetValue(typeof(T), out var value2))
{
value2 = (EventHandler)Delegate.Remove(value2, value);
if (value2 == null)
{
delegates.Remove(typeof(T));
}
else
{
delegates[typeof(T)] = value2;
}
}
delegatesLookup.Remove(del);
}
}
}