C# Dynamic Event Subscription

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

    This method adds to an event, a dynamic handler that calls a method OnRaised, passing the event parameters as an object array:

    void Subscribe(object source, EventInfo ev)
    {
        var eventParams = ev.EventHandlerType.GetMethod("Invoke").GetParameters().Select(p => Expression.Parameter(p.ParameterType)).ToArray();
        var eventHandler = Expression.Lambda(ev.EventHandlerType,
            Expression.Call(
                instance: Expression.Constant(this),
                method: typeof(EventSubscriber).GetMethod(nameof(OnRaised), BindingFlags.NonPublic | BindingFlags.Instance),
                arg0: Expression.Constant(ev.Name),
                arg1: Expression.NewArrayInit(typeof(object), eventParams.Select(p => Expression.Convert(p, typeof(object))))),
            eventParams);
        ev.AddEventHandler(source, eventHandler.Compile());
    }
    

    OnRaised has this signature:

    void OnRaised(string name, object[] parameters);
    

提交回复
热议问题