Why can't these generic type parameters be inferred?

感情迁移 提交于 2019-12-05 18:04:11

You have the constraint TRequest : IRequest<TResponse>, but that doesn't mean that TResponse can be automatically inferred from TRequest. Consider that classes can implement multiple interfaces and TRequest may implement several IRequest<TResponse> types; you may not be doing this in your own design, but it would be pretty complicated for the compiler to have to trudge through the entire class hierarchy to infer that particular parameter.

Long story short, the Handle method takes two generic type parameters (TRequest and TResponse) and you're only giving it one that it can actually use. Inferrence only happens on the actual type arguments, not the types that they inherit or implement.

I think this depends on the usage...

In this case, something (you don't list it above) is calling service.Handle(request);

If the consuming class does not include the generic type in it's own declaration, I think you will run into this problem.

For example... (this won't work)

public class MyClass
{
     var service = new HandlingService();
     var request = new GetCustomerByIdRequest { CustomerId = 1234 };
     var response = service.Handle(request);
}

This should work... (the class needs to know what TResponse is)

public class MyClass<TResponse> where TResponse : YOURTYPE
{
     var service = new HandlingService();
     var request = new GetCustomerByIdRequest { CustomerId = 1234 };
     var response = service.Handle(request);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!