【问题标题】:How can I make a MethodCallExpression for a method?如何为方法创建 MethodCallExpression?
【发布时间】:2016-07-04 04:33:08
【问题描述】:

如果我有方法名和方法的参数,如何为方法创建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”

附加信息:找到不明确的匹配项。

【问题讨论】:

  • 使用方法名时,必须与命名空间结合。
  • @moller1111 我很确定这不是真的。
  • 它给出了一个例外,因为可以为您的方法名称找到多个匹配项。基本上,可以肯定的是,同名和框架抛出了许多重载。您可以通过传递正确的参数类型来指定确切的重载来解决歧义。使用Type.GetMethod(string, Type[])重载。
  • 它给出了一个模棱两可的匹配异常,因为他试图在 MethodInfo 类上调用 Invoke(它有几个重载,可能其中一些是 objectparam object),而不是 HandleEventWithArg 在他的实例上,就像 OP 似乎想要做的那样

标签: c# ambiguous


【解决方案1】:

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

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

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 的表达式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-21
    • 2011-03-07
    • 2021-04-07
    • 2021-12-17
    • 2010-10-26
    • 2011-06-26
    • 2021-09-12
    • 2019-08-31
    相关资源
    最近更新 更多