Skip to content

Instantly share code, notes, and snippets.

@jflam
Created January 15, 2011 00:17
Show Gist options
  • Save jflam/780554 to your computer and use it in GitHub Desktop.
Save jflam/780554 to your computer and use it in GitHub Desktop.
Dynamic Invocation via DLR
static object InvokeInstanceMethod(object thisParameter, string methodName, Type[] typeArguments, params object[] args) {
CSharpArgumentInfo[] parameterFlags = new CSharpArgumentInfo[args.Length + 1];
Expression[] parameters = new Expression[args.Length + 1];
var thisParameterFlags = CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null);
parameterFlags[0] = thisParameterFlags;
parameters[0] = Expression.Constant(thisParameter);
for (int i = 0; i < args.Length; i++) {
parameterFlags[i + 1] = CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant | CSharpArgumentInfoFlags.UseCompileTimeType, null);
parameters[i + 1] = Expression.Constant(args[i]);
}
CallSiteBinder csb = Binder.InvokeMember(CSharpBinderFlags.None, methodName, typeArguments, typeof(Program), parameterFlags);
return Expression.Lambda(
Expression.Dynamic(csb, typeof(object), parameters)
).Compile().DynamicInvoke();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment