如何为方法创建MethodCallExpression?

时间:2016-07-04 04:33:09

标签: c# ambiguous

如果我有方法名称和方法的参数,我该如何为方法创建MethodCallExpression

以下是一个示例方法:

public void HandleEventWithArg(int arg) 
{ 

}

以下是我的代码:

var methodInfo = obj.GetType().GetMethod("HandleEventWithArg");
var body = Expression.Call(Expression.Constant(methodInfo), methodInfo.GetType().GetMethod("Invoke"), argExpression);

以下是例外:

  

未处理的类型异常   mscorlib.dll中出现'System.Reflection.AmbiguousMatchException'

     

其他信息:找到了模糊匹配。

1 个答案:

答案 0 :(得分:1)

我不确定这对你是否合适,但你的调用表达式构造对我来说是错误的(你试图创建一个调用方法信息的Invoke方法的表达式,而不是实际的你的类型的方法。

要创建在您的实例上调用方法的表达式,请执行以下操作:

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:我猜测argExpression是一个表达式,其中包含您的方法所期望的int

相关问题