Reputation: 8357
If I have a method name, and the parameters for the method, how can I create a MethodCallExpression
for the method?
Here is an example method:
public void HandleEventWithArg(int arg)
{
}
Here is the code that I have:
var methodInfo = obj.GetType().GetMethod("HandleEventWithArg");
var body = Expression.Call(Expression.Constant(methodInfo), methodInfo.GetType().GetMethod("Invoke"), argExpression);
Here is the exception:
An unhandled exception of type 'System.Reflection.AmbiguousMatchException' occurred in mscorlib.dll
Additional information: Ambiguous match found.
Upvotes: 3
Views: 2797
Reputation: 28272
I'm not sure if this is ok with you, but your construction of the call expression looks wrong to me (you are trying to create a expression that calls your method info's Invoke
method, instead of the actual method on your type.
To create a expression that calls your method on your instance, do this:
var methodInfo = obj.GetType().GetMethod("HandleEventWithArg");
// Pass the instance of the object you want to call the method
// on as the first argument (as an expression).
// Then the methodinfo of the method you want to call.
// And then the arguments.
var body = Expression.Call(Expression.Constant(obj), methodInfo, argExpression);
PS: I'm guessing argExpression
is an expression with the int
that your method expects
Upvotes: 2