C# 使用反射调用具有参数的方法
我试图调用一个使用反射的参数的方法。它正在返回System.Reflection.TargetParameterCountException 这只发生在方法参数中包含params关键字的方法上C# 使用反射调用具有参数的方法,c#,reflection,C#,Reflection,我试图调用一个使用反射的参数的方法。它正在返回System.Reflection.TargetParameterCountException 这只发生在方法参数中包含params关键字的方法上 Public static dynamic Function(JObject data, string PathFunction) { string MethodName = "MergeFields"; string FunctionsNames
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();
}
如果你有一个方法:
public static string MergeFields(params string[] data)
你打电话:
MergeFields("a", "b", "c");
编译器秘密地将其转换为:
MergeFields(new string[] { "a", "b", "c" });
但是,当您使用反射时,这里没有编译器的帮助!您需要自己创建该字符串数组:
object[] parameterArray = new object[] { new string[] { "274-84-3068", "5", "1", "Hugenberg", "4", "0" } };
这里我们将向MergeFields
传递一个参数,该参数是一个字符串数组