private Dictionary <Type, ListenerInfo> CreateListenerInfos(Type eventType, IEnumerable <IEventListener> allListeners) { Dictionary <Type, ListenerInfo> result = new Dictionary <Type, ListenerInfo>(); foreach (var listener in allListeners) { Type listenerType = listener.GetType(); var baseType = listener.GetType().GetInterface(typeof(IEventListener <>).FullName); if (baseType == null) { result[listenerType] = new ListenerInfo() { ListenerType = listenerType, ListenerEventType = null, CanTrigger = false }; continue; } Type argType = baseType.GetGenericArguments()[0]; bool canTrigger = argType.IsAssignableFrom(eventType); result[listenerType] = new ListenerInfo() { ListenerType = listenerType, CanTrigger = canTrigger, ListenerEventType = argType };; } return(result); }
/// <summary> /// Create Listener MethodInvoker with Emit /// </summary> /// <param name="listenerType"></param> /// <param name="info"></param> /// <returns></returns> private Action <IEventListener, object> CreateListenerTrigger(Type listenerType, ListenerInfo info) { DynamicMethod method = new DynamicMethod("TriggerMethod", null, new Type[] { typeof(IEventListener), typeof(object) }); var il = method.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Castclass, listenerType); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Castclass, info.ListenerEventType); il.Emit(OpCodes.Callvirt, listenerType.GetMethod("Handle", new Type[] { info.ListenerEventType })); il.Emit(OpCodes.Ret); return((Action <IEventListener, Object>)method.CreateDelegate(typeof(Action <IEventListener, Object>))); }