【发布时间】:2019-05-18 17:44:47
【问题描述】:
我正在尝试通过反射调用泛型方法。我需要传递实现此方法期望参数的接口的类的对象。我收到 System.ArgumentException 告诉我“'ReflectionTest.MyRequest' 类型的对象无法转换为 '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);
}
}
有没有人建议我做错了什么?不幸的是,我不擅长反思,所以欢迎任何帮助。
git repo 示例:https://github.com/alan994/ReflectionProblem
【问题讨论】:
标签: c# .net generics reflection