我目前正在学习C#中的Reflection。我使用后期绑定从类中调用2个方法。第一种方法(SumNumbers)有效。第二种方法(SumArray)抛出一个异常,说"参数计数不匹配"。有人可以告诉我如何将整数数组传递给这个方法吗?
>>> from itertools import groupby
>>> a, b = [list(g) for _, g in groupby(d.values(), type)]
>>> dict(Counter(a[0] + b))
{'NTS': 1, 'VAL': 1, 'PRS': 1, 'MRS': 2}
包含2种方法的类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace ReflectionWithLateBinding
{
public class Program
{
static void Main()
{
//load the current executing assembly
Assembly executingAssembly1 = Assembly.GetExecutingAssembly();
//load and instantiate the class dynamically at runtime - "Calculator class"
Type calculatorType1 = executingAssembly1.GetType("ReflectionWithLateBinding.Calculator");
//Create an instance of the type --"Calculator class"
object calculatorInstance1 = Activator.CreateInstance(calculatorType1);
//Get the info of the method to be executed in the class
MethodInfo sumArrayMethod1 = calculatorType1.GetMethod("SumArray");
object[] arrayParams1 = new object[4];
arrayParams1[0] = 5;
arrayParams1[1] = 8;
arrayParams1[2] = 2;
arrayParams1[3] = 1;
int sum1;
//Call "SumArray" Method
sum1 = (int)sumArrayMethod.Invoke(calculatorInstance, arrayParams1);
Console.WriteLine("Sum = {0}", sum1);
Console.ReadLine();
}
}
}
答案 0 :(得分:4)
您没有将整数数组传递给反射方法,而是传递具有4个整数值的对象数组。这将导致反射想要找到具有4个整数参数的方法。相反,您希望将整数数组作为对象数组中的一个值传递。
更改为:
int[] numbers = { 5, 8, 2, 1 };
object[] arrayParams1 = { numbers };
我还想指出你的Sum方法没有正确写入。你只是将0加到input.Length,而不是数组中存在的值。
你想要
sum += input[i];
最后,根据为什么你想要这样做,在C#中使用dynamic会比使用反射更容易,最终会导致大致相同类型的异常情况(在您正在调用方法的对象。
dynamic calculatorInstance1 = Activator.CreateInstance(calculatorType1);
calculatorInstance1.SumArray(new int[] { 5,8,2,1 });
编辑,完整的工作样本。我唯一做的就是将参数数组更改为上面的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace ReflectionWithLateBinding
{
public class Program
{
static void Main()
{
//load the current executing assembly
Assembly executingAssembly1 = Assembly.GetExecutingAssembly();
//load and instantiate the class dynamically at runtime - "Calculator class"
Type calculatorType1 = executingAssembly1.GetType("ReflectionWithLateBinding.Calculator");
//Create an instance of the type --"Calculator class"
object calculatorInstance1 = Activator.CreateInstance(calculatorType1);
//Get the info of the method to be executed in the class
MethodInfo sumArrayMethod1 = calculatorType1.GetMethod("SumArray");
int[] numbers = { 5, 8, 2, 1 };
object[] arrayParams1 = { numbers };
int sum1;
//Call "SumArray" Method
sum1 = (int)sumArrayMethod1.Invoke(calculatorInstance1, arrayParams1);
Console.WriteLine("Sum = {0}", sum1);
Console.ReadLine();
}
}
public class Calculator
{
public int SumArray(int[] input)
{
int sum = 0;
for (int i = 0; i < input.Length; i++)
{
sum += input[i];
}
return sum;
}
}
}