将通用方法转换为异步导致通用参数出现问题

时间:2018-07-12 07:32:12

标签: c# .net generics async-await task-parallel-library

在名为StaticHelper的静态类中,我具有以下通用的static方法:

public static class StaticHelper
{
    public static TResponse GenericMethod<TResponse, TRequest>(TRequest request,
                                                           Func<TRequest, TResponse> method)
    where TRequest  : BaseRequest
    where TResponse : BaseResponse, new()
{
    // ...
}

Func<TRequest, TResponse> methodGenericMethod所调用的方法的名称。 GenericMethod用作WCF方法的包装,用于记录请求/响应等:

public override SomeCustomResponse Request(SomeCustomRequest request)
{
    // GenericMethod above called here
    return StaticHelper.GenericMethod(request, ExecuteRequest));
}

private SomeCustomResponse ExecuteRequest(SomeCustomRequest request)
{
    // ...
}

我现在正尝试创建与async等价的内容:

public static async Task<TResponse> GenericMethodAsync<TResponse, TRequest>(TRequest request,
                                                           Func<TRequest, TResponse> method)
    where TRequest  : BaseRequest
    where TResponse : BaseResponse, new()
{
    // ...
}

// i have removed the override keyword here as I don't need it
public async Task<SomeCustomResponse> Request(SomeCustomRequest request)
{
    // GenericMethodAsync above called here
    return await StaticHelper.GenericMethodAsync(request, ExecuteRequest));
}

private async Task<SomeCustomResponse> ExecuteRequest(SomeCustomRequest request)
{
    // ...
}

这最终导致两个错误:

public async Task<SomeCustomResponse> Request(SomeCustomRequest request)中(第二个异步方法):

  

1)类型Task<SomeCustomResponse>不能用作通用类型或方法“ TResponse”中的类型参数“ StaticHelper.GenericMethodAsync<TResponse, TRequest>(TRequest, Func<TRequest, TResponse>)”。没有从Task<SomeCustomResponse>BaseResponse的隐式引用转换

...并且:

  

2)Task<SomeCustomResponse>必须是具有公共无参数构造函数的非抽象类型,以便在通用类型或方法TResponse StaticHelper.GenericMethodAsync<TResponse, TRequest>(TRequest, Func<TRequest, TResponse>)”

更新:以下René的回答使错误消失了。我现在有一个新的:

  

无法将类型'Task<TResponse>'隐式转换为'TResponse'

有问题的行位于StaticHelper.GenericMethodAsync中,它试图执行Func

var response = method(request); // <-- Cannot implicitly convert type 'Task<TResponse>' to 'TResponse'

...而且显然,解决方案是简单地await

var response = await method(request);

1 个答案:

答案 0 :(得分:6)

您需要更改GenericMethodAsync的声明,因为methodExecuteRequest)的返回类型现在是Task<TResponse>而不是TResponse:< / p>

public static async Task<TResponse> GenericMethodAsync<TResponse, TRequest>(
                     TRequest request,
                     Func<TRequest, Task<TResponse>> method) // <-- change here
                            where TRequest  : BaseRequest
                            where TResponse : BaseResponse, new()
{
    // ...
}

并考虑将ExecuteRequest重命名为ExecuteRequestAsync

当然,您现在必须相应地更改methodGenericMethodAsync的使用:

var response = await method(request);