给定以下接口/类:
public interface IRequest<TResponse> { }
public interface IHandler<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
TResponse Handle(TRequest request);
}
public class HandlingService
{
public TResponse Handle<TRequest, TResponse>(TRequest request)
where TRequest : IRequest<TResponse>
{
var handler = container.GetInstance<IHandler<TRequest, TResponse>>();
return handler.Handle(request);
}
}
public class CustomerResponse
{
public Customer Customer { get; set; }
}
public class GetCustomerByIdRequest : IRequest<CustomerResponse>
{
public int CustomerId { get; set; }
}
如果我尝试编写如下内容,为什么编译器不能推断出正确的类型:
var service = new HandlingService();
var request = new GetCustomerByIdRequest { CustomerId = 1234 };
var response = service.Handle(request); // Shouldn't this know that response is going to be CustomerResponse?
我只是收到“无法推断类型参数”消息。这通常是泛型类型推断的限制,还是有办法使它工作?