遗忘海岸

江湖程序员 -Feiph(LM战士)

导航

使用反射动态绑定与移除方法

        public void AddPublisher(object publisher, string eventName)
        {
            publishers.Add(publisher);
            EventInfo targetEvent = publisher.GetType().GetEvent(eventName);
            GuardEventExists(eventName, publisher, targetEvent);

            MethodInfo addEventMethod = targetEvent.GetAddMethod();
            GuardAddMethodExists(targetEvent);//检测是否存在这样的方法

            EventHandler newSubscriber = OnPublisherFiring;
            addEventMethod.Invoke(publisher, new object[] { newSubscriber });
        }

        public void RemovePublisher(object publisher, string eventName)
        {
            publishers.Remove(publisher);
            EventInfo targetEvent = publisher.GetType().GetEvent(eventName);
            GuardEventExists(eventName, publisher, targetEvent);

            MethodInfo removeEventMethod = targetEvent.GetRemoveMethod();
            GuardRemoveMethodExists(targetEvent);

            EventHandler subscriber = OnPublisherFiring;
            removeEventMethod.Invoke(publisher, new object[] {subscriber});
        }

posted on 2011-03-17 09:27  遗忘海岸  阅读(342)  评论(1编辑  收藏  举报