MethodInfo.Invoke参数顺序

我正在尝试使用reflection来调用方法。

像这样的东西:

method.Invoke(instance, propValues.ToArray()) 

问题是没有办法确保参数数组的顺序正确。 有没有办法具体说明哪个值依赖于哪个参数? 或者我真的需要制作自定义活页夹吗? 如果是这样,有人能引导我朝正确的方向发展吗?

有没有办法具体说明哪个值依赖于哪个参数?

好吧,你按参数顺序指定它们。 因此,如果要将特定值映射到特定名称,则应使用method.GetParameters获取参数列表并以此方式映射它们。 例如,如果你有一个Dictionary带有参数:

 var arguments = method.GetParameters() .Select(p => dictionary[p.Name]) .ToArray(); method.Invoke(instance, arguments); 

编辑:此答案侧重于参数类型而不是参数名称。 如果代码被混淆(或具有不同的param名称),则很难映射Jon Skeet提供的解决方案。

无论如何,我一直在玩这个……这对我来说最有效(不知道参数名称):

  public object CallMethod(string method, params object[] args) { object result = null; // lines below answers your question, you must determine the types of // your parameters so that the exact method is invoked. That is a must! Type[] types = new Type[args.Length]; for (int i = 0; i < types.Length; i++) { if (args[i] != null) types[i] = args[i].GetType(); } MethodInfo _method = this.GetType().GetMethod(method, types); if (_method != null) { try { _method.Invoke(this, args); } catch (Exception ex) { // instead of throwing exception, you can do some work to return your special return value throw ex; } } return result; } 

所以,你可以调用上面的函数:

  object o = CallMethod("MyMethodName", 10, "hello", 'a'); 

上面的调用应该能够使用匹配的签名调用此方法:

 public int MyMethodName(int a, string b, char c) { return 1000; } 

请注意,他上面的示例是在' this '的范围内