简体   繁体   中英

Call a Method which has params using Reflection

I am trying to call a method that has Params using reflection. It is returning System.Reflection.TargetParameterCountException

This is happening only to the methods which have params keyword in method parameters

Public static dynamic Function(JObject data, string PathFunction) {            

        string MethodName = "MergeFields";
        string FunctionsNamespace ="Test.Functions";

        Object[] parameterArray = {"274-84-3068","5","1","Hugenberg","4","0"}

        // Call Static class functions 
        Type type = Type.GetType(FunctionsNamespace);            
        Object obj = Activator.CreateInstance(type);            
        MethodInfo methodInfo = type.GetMethod(MethodName);            
        object st =  methodInfo.Invoke(obj, parameterArray);
        return st;

    }



     public static string MergeFields(params string[] data)
    {
        StringBuilder sb = new StringBuilder();
       // code to be processed
        return sb.ToString();
    }

If you've got a method:

public static string MergeFields(params string[] data)

and you call:

MergeFields("a", "b", "c");

the compiler secretly turns that into:

MergeFields(new string[] { "a", "b", "c" });

However when you're using reflection, you don't get the compiler's help here: You'll need to create that string array yourself:

object[] parameterArray = new object[] { new string[] { "274-84-3068", "5", "1", "Hugenberg", "4", "0" } };

Here we are going to pass a single parameter to MergeFields , and that parameter is an array of strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM