使用反射动态绑定与移除方法
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});
}