Ejemplo n.º 1
0
        /// <summary>
        /// 注册事件
        /// </summary>
        /// <param name="eventType">事件名</param>
        /// <param name="listener">监听者</param>
        public static void RegisterEvent(string eventType, object listener)
        {
            Type type = listener.GetType();

            MethodInfo[] methodInfos = type.GetMethods();
            foreach (MethodInfo methodInfo in methodInfos)
            {
                EventAttr eventAttr = (EventAttr)methodInfo.GetCustomAttribute(typeof(EventAttr), false);
                if (eventAttr == null || eventAttr.EventType != eventType)
                {
                    continue;
                }
                RegisterEvent(eventType, methodInfo, listener);
            }
        }
Ejemplo n.º 2
0
        ///// <summary>
        ///// 注册事件 最懒的方式不推荐使用
        ///// </summary>
        ///// <param name="assembly">程序集</param>
        //public static void Register(Assembly assembly, bool isFormOrControl = false)
        //{
        //    var types = assembly.ExportedTypes;
        //    foreach (var type in types)
        //    {
        //        if (isFormOrControl)
        //        {
        //            if (typeof(Form).IsAssignableFrom(type) || typeof(Control).IsAssignableFrom(type))
        //            {
        //                object instance = Activator.CreateInstance(type);
        //                RegisterEvent(instance);
        //            }
        //        }
        //        else
        //        {
        //            object instance = Activator.CreateInstance(type);
        //            RegisterEvent(instance);
        //        }
        //    }
        //}

        /// <summary>
        /// 注册事件
        /// </summary>
        /// <param name="listener">监听者</param>
        public static void RegisterEvent(object listener)
        {
            Type type = listener.GetType();

            MethodInfo[] methodInfos = type.GetMethods();
            foreach (MethodInfo methodInfo in methodInfos)
            {
                EventAttr eventAttr = (EventAttr)methodInfo.GetCustomAttribute(typeof(EventAttr), false);
                if (eventAttr != null)
                {
                    string eventType = eventAttr.EventType;
                    if (string.IsNullOrEmpty(eventType))
                    {
                        eventType = methodInfo.Name;
                    }
                    RegisterEvent(eventType, methodInfo, listener);
                }
            }
        }