在名为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>
”违规行位于试图执行
TResponse
的StaticHelper.GenericMethodAsync
中:var response = method(request); // <-- Cannot implicitly convert type 'Task<TResponse>' to 'TResponse'
……很明显,解决办法就是:
var response = await method(request);
最佳答案
您需要更改GenericMethodAsync
的声明,因为method
(ExecuteRequest
)的返回类型现在是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);