在名为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> method是由GenericMethod调用的方法的名称。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>)”隐式转换为“Task<TResponse>
违规行位于试图执行TResponseStaticHelper.GenericMethodAsync中:
var response = method(request); // <-- Cannot implicitly convert type 'Task<TResponse>' to 'TResponse'

……很明显,解决办法就是:
var response = await method(request);

最佳答案

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

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
当然,现在必须相应地更改method内部GenericMethodAsync的用法:
var response = await method(request);

09-30 21:53