c# - MethodInfo.Invoke参数顺序

标签 c# reflection

我正在尝试使用反射调用方法。

像这样:

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/

相关文章:

c# - Mono:如何在新的控制台/终端窗口上运行 bash 命令?

c# - 关闭windows框C#

c# - 保存 Site.master 回发事件中的 <LI> 类值

Java 反射 : Getting fields and methods in declaration order

php - 实例化一个对象而不在 PHP 中调用它的构造函数

c# - 将 DropDownListFor 与 ViewModel 上的列表绑定(bind)

c# - 当只有一个参数c#时,我可以通过反射创建一个实例并指定重载的 "params"构造函数吗?

android - 为什么我的 Android 应用程序会因 java.lang.ExceptionInInitializerError 强制关闭,并且没有被 try/catch block 捕获?

c# - 转换枚举?到整数?使用反射时失败

c# - 如何将 Expression<Func<BaseClass, bool>> 转换为 Expression<Func<InheritedClass, bool>>?