Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class EventManager
- {
- public static void Subscribe<T>(Action<T> handler) where T : GameEvent
- {
- EventManagerInternal<T>.Subscribe(handler);
- }
- public static void Unsubscribe<T>(Action<T> handler) where T : GameEvent
- {
- EventManagerInternal<T>.Unsubscribe(handler);
- }
- public static void Raise<T>(T e) where T : GameEvent
- {
- EventManagerInternal<T>.Raise(e);
- }
- private static class EventManagerInternal<T> where T : GameEvent
- {
- private static Dictionary<Type, Action<T>> dic = new Dictionary<Type, Action<T>>();
- public static void Subscribe(Action<T> handler)
- {
- Type type = typeof(T);
- if (!dic.ContainsKey(type)) {
- dic[type] = handler;
- Console.WriteLine("Registered new type: " + type);
- }
- else {
- // make sure the handler doesn't exist first
- bool hasHandlerSubscribed = dic[type].GetInvocationList().Any(h => h.Equal(shandler));
- if (hasHandlerSubscribed) {
- Console.WriteLine(handler.Method.Name + " has already subbed to an event of type " + type);
- return;
- }
- dic[type] += handler;
- }
- Console.WriteLine("Method " + handler.Method.Name + " has subbed to receive notifications from " + type);
- }
- public static void Unsubscribe(Action<T> handler)
- {
- Type type = typeof(T);
- // make sure the type exists
- if (!dic.ContainsKey(type)) {
- Console.WriteLine("Type " + type + " hasn't registered at all, it doesn't have any subscribers... at least not in my book...");
- return;
- }
- // remove the handler from the chain
- dic[type] -= handler;
- // if there's no more subscribers to the "type" entry, remove it
- if (dic[type] == null) {
- dic.Remove(type);
- Console.WriteLine("No more subscribers to " + type);
- }
- }
- public static void Raise(T e)
- {
- Action<T> handler;
- if (dic.TryGetValue(e.GetType(), out handler)) {
- handler.Invoke(e);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment