c# - 通过反射调用带有参数的泛型方法时,无法将 System.Int32 类型的对象转换为 System.Object[]

标签 c# .net generics reflection invoke

别说我有一些带有两个构造函数的类(没有参数和有参数):

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/

相关文章:

c# - datagridview鼠标悬停事件如何判断你在哪一列

c# - 您会使用什么报告工具?

c# - ValueInjecter:如何在执行 .InjectFrom<UnflatLoopValueInjection>(data) 时忽略某些属性?

Java ArrayList indexOf 泛型类型

c# - 在锁定的系统上渲染 3D 场景

c# - 应用程序之间的剪贴板传输

C#字节数组转字符串

使用变量泛型作为值的 Java Map

Java泛型函数

c# - 如何让 Web Api 查询字符串参数绑定(bind)保持 UTC 日期?