|
- using System;
- using System.Collections.Generic;
-
- namespace SUISS.Core
- {
- public class Messenger
- {
- public void Subscribe<T>(Action<T> callback) where T : class
- {
- Action<object> action = delegate (object o)
- {
- callback((T)((object)o));
- };
- if (this.events.ContainsKey(typeof(T)))
- {
- this.events[typeof(T)] = (Action<object>)Delegate.Combine(this.events[typeof(T)], action);
- }
- else
- {
- this.events.Add(typeof(T), action);
- }
- this.lookupTable.Add(callback, action);
- }
-
- public void Unsubscribe<T>(Action<T> callback) where T : class
- {
- if (this.events.ContainsKey(typeof(T)) && this.lookupTable.ContainsKey(callback))
- {
- (this.events)[typeof(T)] = (Action<object>)Delegate.Remove(this.events[typeof(T)], this.lookupTable[callback]);
- this.lookupTable.Remove(callback);
- }
- }
-
- public void Invoke<T>(T evt) where T : class
- {
- Action<object> action;
- if (this.events.TryGetValue(typeof(T), out action) && action != null)
- {
- action(evt);
- }
- }
-
- private Dictionary<Type, Action<object>> events = new Dictionary<Type, Action<object>>();
-
- private Dictionary<object, Action<object>> lookupTable = new Dictionary<object, Action<object>>();
- }
- }
|