我正在尝试使用反射来调用方法。
这样的事情:
method.Invoke(instance, propValues.ToArray())
问题是没有办法确保参数数组的顺序正确。有没有办法具体说明哪个值按名称在哪个参数上进行?或者我真的需要制作自定义活页夹吗?如果是这样,任何人都能引导我朝着正确的方向前进吗?
答案 0 :(得分:7)
有没有办法具体说明哪个值按名称在哪个参数上进行?
好吧,您可以按参数顺序指定它们。因此,如果要将特定值映射到特定名称,则应使用method.GetParameters
获取参数列表并以此方式映射它们。例如,如果您有Dictionary<string, object>
参数:
var arguments = method.GetParameters()
.Select(p => dictionary[p.Name])
.ToArray();
method.Invoke(instance, arguments);
答案 1 :(得分:0)
编辑:此答案侧重于参数类型而非参数名称。如果代码被混淆(或具有不同的参数名称),则很难映射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
”