在名为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)
StaticHelper.GenericMethodAsync<TResponse, TRequest>(TRequest, Func<TRequest, TResponse>)”Task<SomeCustomResponse>
必须是具有公共无参数构造函数的非抽象类型,以便在通用类型或方法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);
答案 0 :(得分:6)
您需要更改GenericMethodAsync
的声明,因为method
(ExecuteRequest
)的返回类型现在是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
。
当然,您现在必须相应地更改method
中GenericMethodAsync
的使用:
var response = await method(request);