3

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.

Simon
  • 7,991
  • 21
  • 83
  • 163
  • When you use method name, you have to combine it with namespace. – A.B. Jul 04 '16 at 04:54
  • @moller1111 I am fairly sure that is not true. – nawfal Jul 04 '16 at 05:04
  • 1
    It gives an exception because multiple matches could be found for your method name. Basically there are many overloads for the same name and framework throws to be sure. You can resolve ambiguity by specifying exact overload by passing the right parameter types. Use `Type.GetMethod(string, Type[])` overload. – nawfal Jul 04 '16 at 05:06
  • It gives an ambiguous match exception because he is trying to call `Invoke` on the class `MethodInfo` (which has several overloads, and probably some of them being `object` and `param object`), and not `HandleEventWithArg` on his instance, like the OP seems to want to do – Jcl Jul 04 '16 at 05:15

1 Answers1

2

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);

I've made a fiddle

PS: I'm guessing argExpression is an expression with the int that your method expects

Jcl
  • 27,696
  • 5
  • 61
  • 92