为什么不能将这些泛型类型参数推断? [英] Why can't these generic type parameters be inferred?

查看:550
本文介绍了为什么不能将这些泛型类型参数推断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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; }
}



为什么不能编译器推断出正确的类型,如果我尝试写类似以下内容:

Why can't the compiler infer the correct types, if I try and write something like the following:

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?



我刚刚得到的类型参数无法推断的消息。这与一般通用的类型推断的限制,还是有办法,使这项工作?

I just get the 'type arguments cannot be inferred' message. Is this a limitation with generic type inference in general, or is there a way to make this work?

推荐答案

您有约束 TRequest:IRequest< TResponse> ,但这并不意味着 TResponse 可自动从<$ C $推断C> TRequest 。考虑到类可以实现多个接口和 TRequest 可以实现的若干个 IRequest< TResponse> 类型;你可能不会在自己的设计中这样做,但是这将是非常复杂的编译器必须通过整个类层次结构跋涉来推断该特定参数。

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.

长话短说,在处理方法需要的两个泛型类型参数( TRequest TResponse )和你只给它一个它可以实际使用。 Inferrence只发生在的实际的类型参数,而不是他们继承或实现的类型。

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.

这篇关于为什么不能将这些泛型类型参数推断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆