常见的 C# 泛型类型推断

C# Generics type inference for comman

我必须使用我无法控制的特定 API:

TResponse Request<TRequest, TResponse>(TRequest request) 
    where TRequest : class 
    where TResponse : class;

这是 EasyNetQ 库中 RabbitMq 的 RPC 包装器

我希望有一些方法来定义 TRequest 到 TResponse 的关系,这样我就不必像这样每次调用都手动匹配它们:

this._client.Request<CancelPaymentByMerchantRequest, CancelPaymentByMerchantResponse>(request);

我想到的解决办法是:

public interface ICommand<TRequest, TResponse> { }

public class StartCommand : ICommand<StartCommand, StartResponse>
{
    public int Id { get; set; }

    public string Args { get; set; }
}

public class StartResponse
{
    public bool Success { get; set; }

    public string Error { get; set; }
}

它的消费者:

 public TResponse Send<TRequest, TResponse>(ICommand<TRequest, TResponse> payload)
            where TRequest : class
            where TResponse : class
        {
            var result = client.Request<TRequest, TResponse>((TRequest)payload);
            return result;
        }

是否可以去掉 ICommand 标记接口上的 TRequest 类型?

我也担心与标记接口相关的额外成本,然后在实际的库调用中直接从中转换。

如有任何建议,我们将不胜感激。

实现此目的的最简单方法就是为每个 TRequest 类型添加一次围绕 Send 的抽象:

public SpecificResponse Send(SpecificRequest payload)
{
    return Send<SpecificRequest, SpecificResponse>(payload);
}

您必须为每个 TRequest, TResponse 对定义 Send 的重载,然后您的应用程序的其余部分可以使用这些 "strongly-typed" 版本以避免必须在各处重述关系.

你如何编排这取决于你,但我更喜欢每个 request/response 类型的 interface/class 作为通用层的中介(或者一个带有一堆合同的大接口它也可以工作。