samedi 18 mai 2019

Call generic method by reflection. System.ArgumentException happens

I'm trying to call generic method via reflection. I need to pass object of class that implements interface this method expects for parameter. I'm getting System.ArgumentException telling me 'Object of type 'ReflectionTest.MyRequest' cannot be converted to type 'ReflectionTest.IRequest`1[ReflectionTest.MyRequest]'.'

class Program
{
    static void Main(string[] args)
    {
        var request = new MyRequest();
        IMediator mediator = new Mediator();

        //This works (of course), but I need to call this by reflection. I don't know the type at design time.
        //var r = mediator.Send(request);

        //I tried this, but it doesn't work
        var type = request.GetType();
        var method = mediator.GetType().GetMethod("Send");
        var generic = method.MakeGenericMethod(type);
        //Exception
        var response = generic.Invoke(mediator, new object[] { request });

    }
}

public interface IRequest<out TResponse>
{

}

public interface IMediator
{
    TResponse Send<TResponse>(IRequest<TResponse> requests);
}

public class MyRequest : IRequest<MyResponse>
{
}

public class MyResponse
{
}

public class Mediator : IMediator
{
    public TResponse Send<TResponse>(IRequest<TResponse> requests)
    {
        Console.WriteLine("Processing...");
        return default(TResponse);
    }
}

Has anyone have some suggestion what I'm doing wrong? Unfortunately, I'm not that skilled with reflection so any help is welcome.

Sample git repo: https://github.com/alan994/ReflectionProblem





Aucun commentaire:

Enregistrer un commentaire