C# Dynamic Event Subscription

前端 未结 9 1886
無奈伤痛
無奈伤痛 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:25

    It is possible to subscribe to an event using Reflection

    var o = new SomeObjectWithEvent;
    o.GetType().GetEvent("SomeEvent").AddEventHandler(...);
    

    http://msdn.microsoft.com/en-us/library/system.reflection.eventinfo.addeventhandler.aspx

    Now here is going to be the problem that you are going to have to solve. The delegates required for each event handler will have different signatures. You are going to have to find away to create these methods dynamically, which probably means Reflection.Emit, or you are going to have to limit your self to a certain delegate so that you can handle it with compiled code.

    Hope this helps.

提交回复
热议问题