Reputation: 76
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();
}
Upvotes: 0
Views: 67
Reputation: 42330
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.
Upvotes: 3