我正在尝试使用反射调用方法。
像这样:
method.Invoke(instance, propValues.ToArray())
问题是没有办法确保参数数组的顺序正确。有没有办法通过名称指定哪些值适用于哪个参数?或者我真的必须制作自定义 Binder 吗?如果是这样,谁能指导我正确的方向?
最佳答案
Is there a way to specific which values goes on which parameter by name?
好吧,您按参数顺序指定它们。因此,如果你想将特定值映射到特定名称,你应该使用 method.GetParameters
获取参数列表。并以这种方式映射它们。例如,如果您有一个 Dictionary<string, object>
使用参数:
var arguments = method.GetParameters()
.Select(p => dictionary[p.Name])
.ToArray();
method.Invoke(instance, arguments);
关于c# - MethodInfo.Invoke参数顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11527345/