Dynamic invoke of a method using named parameters

后端 未结 3 988
耶瑟儿~
耶瑟儿~ 2020-12-16 07:41

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

I am wondering if it is possible to mix in Named Parame

相关标签:
3条回答
  • 2020-12-16 08:00

    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);
                if (paramIndex >= 0)
                {
                    parameters[paramIndex] = item.Value;
                }
            }
            return parameters;
        }
    }
    

    And then call it like this:

    var parameters = new Dictionary<string, object>();
    // Add parameters ...
    methodInfo.InvokeWithNamedParameters(obj, parameters);
    
    0 讨论(0)
  • 2020-12-16 08:03

    you can get your paramter names with the help of this article How can you get the names of method parameters? and then you can reorder them to invoke them as described here Reflection: How to Invoke Method with parameters

    0 讨论(0)
  • 2020-12-16 08:06

    With .net4, I have an opensource framework ImpromptuInterface (found in nuget) that makes it easy to use the DLR apis for late invocation including named/optional parameters.

    var result = Impromptu.InvokeMember(target, "MyMethod", parameters.Select(pair=>  InvokeArg.Create(pair.Key, pair.Value)).Cast<object>().ToArray());
    
    0 讨论(0)
提交回复
热议问题