lundi 15 février 2016

Invoking Generic method with params parameter through reflection

I am trying to invoke a generic methods that accepts a single params parameter through reflection. When I picked it to be non generic passing an object[] item seemed to be sufficient but when I reqired to call a generic method it does not work anymore.

var type = typeof (ClassWithGenericMethod);
var method = type.GetMethod("GenericMethod", BindingFlags.Instance | BindingFlags.Public);
var genericMethod = method.MakeGenericMethod(typeof(object));
var result = (bool)genericMethod.Invoke(new ClassWithGenericMethod(), new object[]{"param"});
Assert.IsTrue(result);

The called class:

public class ClassWithGenericMethod
{
    public bool GenericMethod<T>(params string[] input)
    {
        return input.Length == 1;
    }
}

The code fails before the assert with the following exception:

Object of type 'System.String' cannot be converted to type 'System.String[]'.





Aucun commentaire:

Enregistrer un commentaire