jeudi 24 novembre 2016

Unable to cast object of type System.Int32 to System.Object[] when calling generic method with parameters via reflection

Les't say I have some class with two constructors (without parameters and with them):

public class Employee
{
    private int Salary = 0;

    public Employee()
    {
        Salary = 100;
    }

    public Employee(int newSalary)
    {
        Salary = newSalary;
    }
}

And I have some static helper class that have generic methods to call constructors:

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);
    }
}

Lets assume I have Type of class that I need to construct (typeof(Employee) in this particular case) and call it's constructor with the following code:

var method1 = typeof(GenericClassCreator).GetMethod("CreateClassNoParams");
var generic1 = method.MakeGenericMethod(typeof(Employee));

var employee1 = generic.Invoke(null, null);


var method2 = typeof(GenericClassCreator).GetMethod("CreateClassWithParams");
var generic2 = method.MakeGenericMethod(typeof(Employee));

var employee2 = generic.Invoke(null, new object[] { 500 });

Obtaining employee1 (via constructor without parameters) is ok. But obtaining employee2 (via constructor with parameter) throws exception:

Unable to cast object of type System.Int32 to System.Object[] Even if I change

generic.Invoke(null, new object[] { 500 });

to

generic.Invoke(null, new object[] { new object() });

exception is thrown

Unable to cast object of type System.Object to System.Object[]

So what's wrong with my code?





Aucun commentaire:

Enregistrer un commentaire