MethodInfo.Invoke 参数顺序 [英] MethodInfo.Invoke parameter order
问题描述
我正在尝试使用反射调用方法.
I'm trying to invoke a method using reflection.
像这样:
method.Invoke(instance, propValues.ToArray())
问题是没有办法确保参数数组的顺序正确.有没有办法通过名称来指定哪些值在哪个参数上?还是我真的必须制作自定义活页夹?如果是这样,任何人都可以指导我朝着正确的方向前进吗?
The problem is that there isn't a way to ensure the array of parameters is in the right order. Is there a way to specific which values goes on which parameter by name? Or do I really have to make a custom binder? If so, can anyone guide me in the right direction?
推荐答案
有没有办法按名称指定哪些值适用于哪个参数?
Is there a way to specific which values goes on which parameter by name?
好吧,您按参数顺序指定它们.因此,如果要将特定值映射到特定名称,则应使用 method.GetParameters
并以这种方式映射它们.例如,如果您有一个带有参数的 Dictionary
:
Well, you specify them in parameter order. So if you want to map specific values to specific names, you should fetch the parameter list with method.GetParameters
and map them that way. For example, if you had a Dictionary<string, object>
with the parameters:
var arguments = method.GetParameters()
.Select(p => dictionary[p.Name])
.ToArray();
method.Invoke(instance, arguments);
这篇关于MethodInfo.Invoke 参数顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!