别说我有一些带有两个构造函数的类(没有参数和有参数):
public class Employee
{
private int Salary = 0;
public Employee()
{
Salary = 100;
}
public Employee(int newSalary)
{
Salary = newSalary;
}
}
我有一些静态帮助器类,它们具有调用构造函数的通用方法:
public static class GenericClassCreator
{
public static T CreateClassNoParams<T>()
where T : class, new()
{
return new T();
}
public static T CreateClassWithParams<T>(params object[] args)
where T : class
{
return (T)Activator.CreateInstance(typeof(T), args);
}
}
假设我有我需要构造的类类型(在这种特殊情况下为typeof(Employee))并使用以下代码调用它的构造函数:
var method1 = typeof(GenericClassCreator).GetMethod("CreateClassNoParams");
var generic1 = method1.MakeGenericMethod(typeof(Employee));
var employee1 = generic1.Invoke(null, null);
var method2 = typeof(GenericClassCreator).GetMethod("CreateClassWithParams");
var generic2 = method2.MakeGenericMethod(typeof(Employee));
var employee2 = generic2.Invoke(null, new object[] { (object)500 });
获取employee1(通过不带参数的构造函数)就可以了。但是获取 employee2(通过带参数的构造函数)抛出异常:
Unable to cast object of type System.Int32 to System.Object[]
即使我改变
generic.Invoke(null, new object[] { (object)500 });
到
generic.Invoke(null, new object[] { new object() });
抛出异常
Unable to cast object of type System.Object to System.Object[]
那么我的代码有什么问题吗?
最佳答案
您的方法需要一个 object[]
作为参数。 MethodInfo.Invoke
需要一个包含所有参数的 object[]
。这意味着您需要一个包含另一个 object[]
的 object[]
:
var employee2 = generic2.Invoke(null, new object[] { new object[] { 500 } });
关于c# - 通过反射调用带有参数的泛型方法时,无法将 System.Int32 类型的对象转换为 System.Object[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40799457/