views:

49

answers:

0

Hi,

I found your code example below extremely helpful, however I don't understand the use of expressions in the code... I am looking to modify this method to accept a delegate with a params object[] parameter.. any pointers would be greatly appreciated.

Simon Bridge ([email protected])

class EventProxy
{
    static public Delegate Create(EventInfo evt, Action d)
    {
        var handlerType = evt.EventHandlerType;
        var eventParams = handlerType.GetMethod("Invoke").GetParameters();

        //lambda: (object x0, EventArgs x1) => d() 
        var parameters = eventParams.Select(p => Expression.Parameter(p.ParameterType, "x"));
        // - assumes void method with no arguments but can be 
        //   changed to accomodate any supplied method 
        var body = Expression.Call(Expression.Constant(d), d.GetType().GetMethod("Invoke"));
        var lambda = Expression.Lambda(body, parameters.ToArray());
        return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false);
    }
}