C# Dynamic Event Subscription

前端 未结 9 1883
無奈伤痛
無奈伤痛 2020-12-01 03:09

How would you dynamically subscribe to a C# event so that given a Object instance and a String name containing the name of the event, you subscribe to that event and do some

9条回答
  •  离开以前
    2020-12-01 03:44

    Do you mean something like:

    //reflect out the method to fire as a delegate
    EventHandler eventDelegate = 
       ( EventHandler ) Delegate.CreateDelegate(
           typeof( EventHandler ),    //type of event delegate
           objectWithEventSubscriber, //instance of the object with the matching method
           eventSubscriberMethodName, //the name of the method
           true );
    

    This doesn't do the subscription, but will give to the method to call.

    Edit:

    Post was clarified after this answer, my example won't help if you don't know the type.

    However all events in .Net should follow the default event pattern, so as long as you've followed it this will work with the basic EventHandler.

提交回复
热议问题