C# System.Reflection.TargetParameterCountException当参数计数可以是动态的时
“概率论”类中的所有方法都接受参数的动态计数——这意味着可以根据需要放置任意多的参数。但.NET在调用参数中包含“params”关键字的方法时仍会显示“System.Reflection.TargetParameterCountException” 代码如下:C# System.Reflection.TargetParameterCountException当参数计数可以是动态的时,c#,.net,parameters,delegates,invoke,C#,.net,Parameters,Delegates,Invoke,“概率论”类中的所有方法都接受参数的动态计数——这意味着可以根据需要放置任意多的参数。但.NET在调用参数中包含“params”关键字的方法时仍会显示“System.Reflection.TargetParameterCountException” 代码如下: internal static class ProbabilitiesTheory { static public double GetMediumValue(params double[] integers) { } }
internal static class ProbabilitiesTheory
{
static public double GetMediumValue(params double[] integers)
{ }
}
class Program
{
static void Main(string[] args)
{
MethodInfo[] methods = Type.GetType("ConsoleApplication1.ProbabilitiesTheory").GetMethods();
while (true)
{
Console.WriteLine("Write the name of the method\n");
string NameOfMethod = Console.ReadLine();
Console.WriteLine("Write the parameters of the method using the following format:
parameter1;parameter2;parameter3;parameterN\n");
string ParametersOfMethod = Console.ReadLine();
foreach (var i in methods)
{
if (i.Name == NameOfMethod)
{
object[] @parameters = (from t in ParametersOfMethod.Split(';') where t != "" select (object)Convert.ToDouble(t)).ToArray();
i.Invoke(null, @parameters); // Exception HERE
}
}
Console.WriteLine("______");
}
}
}
在这里使用LINQ表达式是完全可以的,我得到了我需要得到的东西:object[]包含动态数量的双值
如何解决这个问题?就反射而言,
params数组
只是一个带有奇特语法糖的数组。您可以通过如下方式调整代码来解决大多数方法的直接问题:
double[] @parameters = (from t in ParametersOfMethod.Split(';') where t != "" select Convert.ToDouble(t)).ToArray();
i.Invoke(null, new[] { @parameters});
其要点是params数组
在运行时只是一个参数,而向其添加可变数量的值的能力只是由编译器完成的
您可以使用以下代码段确认这一点:
void Main()
{
var parameterCount = typeof(Test).GetMethod("Foo").GetParameters().Count();
Console.WriteLine(parameterCount); // Output: 2
}
// Define other methods and classes here
public static class Test
{
public static void Foo(double x, params double[] y)
{}
}
如果在params数组
不是唯一的参数时,需要调用使用用户提供值的params数组
的函数,则需要获取方法参数计数并计算数组实际开始的位置,然后相应地进行包装