/// <summary> /// Dynamic construc delegate using expressions /// </summary> /// <param name="delegateType"></param> /// <param name="func"></param> /// <param name="control_name"></param> /// <param name="event_name"></param> /// <param name="program"></param> /// <returns></returns> public static Delegate BuildDynamicHandle(Type delegateType, Func <object[], object> func, String view_guid, String view_name, String control_name, String event_name, String program) { var invokeMethod = delegateType.GetMethod("Invoke"); ParameterExpression[] parms = invokeMethod.GetParameters().Select(parm => Expression.Parameter(parm.ParameterType, parm.Name)).ToArray(); CctrlEventDesc eDesc = new CctrlEventDesc(view_guid, view_name, control_name, event_name, program); UnaryExpression[] typeAsExpression = new UnaryExpression[] { Expression.TypeAs(System.Linq.Expressions.Expression.Constant(eDesc, typeof(CctrlEventDesc)), typeof(CctrlEventDesc)) }; var instance = func.Target == null ? null : Expression.Constant(func.Target); //var converted = parms.Select(parm => Expression.Convert(parm, typeof(object))).Concat(typeAsExpression); var converted = typeAsExpression.Concat(parms.Select(parm => Expression.Convert(parm, typeof(object)))); NewArrayExpression paramArray = Expression.NewArrayInit(typeof(object), converted); var call = Expression.Call(instance, func.Method, paramArray); var body = invokeMethod.ReturnType == typeof(void) ? (Expression)call : Expression.Convert(call, invokeMethod.ReturnType); var expr = Expression.Lambda(delegateType, body, new ParameterExpression[] { parms[0], parms[1] }); // parms return(expr.Compile()); }