方法的使用命名参数动态调用 [英] Dynamic invoke of a method using named parameters

查看:196
本文介绍了方法的使用命名参数动态调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们目前正在使用.net 3.5,我们的应用程序的一部分使用了动态调用(使用的 MethodBase.Invoke

We're currently using .NET 3.5 and part of our application uses dynamic invocation (using MethodBase.Invoke)

我想知道是否有可能命名参数在混合(在.NET 4中)与动态调用,执行类似的东西:

I am wondering if it is possible to mix in Named Parameters (in .NET 4) with dynamic invocation, to perform something similar to:

// Dictionary that holds parameter name --> object mapping
var parameters = new Dictionary<string, object>();

// Add parameters ....

// Invoke where each parameter will match the one from the method signature.
methodInfo.Invoke(obj, parameters);

有没有任何的API,允许该选项开箱?如果没有,是否可以开发一些解决方案来执行呢?

Is there any API that allows this option out of the box? If not, is it possible to develop some solution to perform this?

编辑:

这个问题的反思,这听起来类似于如何编译器实际上可能需要匹配基于参数列表的方法调用。也许有一些编译器API(或新的罗斯林项目),允许这样做只是这容易吗? (无需编码它自己,这可能是容易出错)。

Rethinking of this problem, it sounds similar to how the compiler may actually need to match method calls based on argument lists. Perhaps there's some Compiler API (or the new Roslyn project) that allows doing just this easily? (without coding it myself which may be prone to errors).

推荐答案

您可以用code是这样的:

You can use code like this:

public static class ReflectionExtensions {

    public static object InvokeWithNamedParameters(this MethodBase self, object obj, IDictionary<string, object> namedParameters) { 
        return self.Invoke(obj, MapParameters(self, namedParameters));
    }

    public static object[] MapParameters(MethodBase method, IDictionary<string, object> namedParameters)
    {
        string[] paramNames = method.GetParameters().Select(p => p.Name).ToArray();
        object[] parameters = new object[paramNames.Length];
        for (int i = 0; i < parameters.Length; ++i) 
        {
            parameters[i] = Type.Missing;
        }
        foreach (var item in namedParameters)
        {
            var paramName = item.Key;
            var paramIndex = Array.IndexOf(paramNames, paramName);
            parameters[paramIndex] = item.Value;
        }
        return parameters;
    }
}

然后调用它是这样的:

And then call it like this:

var parameters = new Dictionary<string, object>();
// Add parameters ...
methodInfo.InvokeWithNamedParameters(obj, parameters);

这篇关于方法的使用命名参数动态调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆