![](/img/trans.png)
[英]C# call generic interface method from non generic parent interface without dynamic
[英]How to call generic Method from generic Interface c#?
錯誤消息:System.ArgumentException:'<>f__AnonymousType2`1[System.String]' 類型的對象無法轉換為'ConsoleApp2.IRequestSimple' 類型
有我的類型請求/響應
public interface IRequestSimple
{
public string Field { get; set; }
}
public interface IResponseSimple
{
public string Answer { get; set; }
}
public class MyConsumer : IConsumer<IRequestSimple>
{
public async Task Consume(ConsumeContext<IRequestSimple> context)
{
Console.WriteLine(context.Message.Field);
await context.RespondAsync<IResponseSimple>(new { Answer = "Good job" });
}
}
我正在嘗試調用 GetResponse 但使用反射
var client = mediator.CreateRequestClient<IRequestSimple>();
var response = client.GetResponse<IResponseSimple>(new { });
有我的問題,我需要指定類型來調用 GetResponse
var requestType = typeof(IRequestSimple);
var responseType = typeof(IResponseSimple);
Type type = mediator.GetType();
var methodInfo = typeof(IClientFactory).GetMethods().Where(s => s.Name == "CreateRequestClient" && s.IsGenericMethod).First();
var genericMethod = methodInfo.MakeGenericMethod(requestType);
dynamic requestClient = genericMethod.Invoke(mediator, new object[] { Missing.Value });
Type type1 = requestClient.GetType();
var methodInfo1 = type1 .GetMethods().Where(s => s.Name == "GetResponse").First();
var genericMethod1 = methodInfo1.MakeGenericMethod(responseType);
//Here is my requestClient should be with specified type
var task = (Task)genericMethod1.Invoke(requestClient, new object[] { new { Field = "1" }, Missing.Value, Missing.Value });
await task.ConfigureAwait(false);
我只是創建方法並調用它
public static async Task<Tout> GetResponse<Tin, Tout>(object request) where Tin : class where Tout : class
{
var requestClient = Program.mediator.CreateRequestClient<Tin>();
var response = await requestClient.GetResponse<Tout>(request);
return response.Message;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.