如果我有一个方法名称和该方法的参数,如何为该方法创建一个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'
附加信息:发现歧义匹配。
最佳答案
我不确定这是否可以,但是您对call表达式的构造对我来说似乎是错误的(您正在尝试创建一个表达式,该表达式调用方法信息的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
表达式关于c# - 如何为方法创建MethodCallExpression?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38177007/