gpt4 book ai didi

c# - 将泛型方法转换为异步导致泛型参数出现问题

转载 作者:太空狗 更新时间:2023-10-30 00:48:00 25 4
gpt4 key购买 nike

在名为 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) The type Task<SomeCustomResponse> cannot be used as type parameter 'TResponse' in the generic type or method 'StaticHelper.GenericMethodAsync<TResponse, TRequest>(TRequest, Func<TRequest, TResponse>)'. There is no implicit reference conversion from Task<SomeCustomResponse> to BaseResponse

...和:

2) Task<SomeCustomResponse> must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TResponse' in the generic type or method StaticHelper.GenericMethodAsync<TResponse, TRequest>(TRequest, Func<TRequest, TResponse>)

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

Cannot implicitly convert type 'Task<TResponse>' to 'TResponse'

违规行在StaticHelper.GenericMethodAsync它试图执行 Func :

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

...显然,解决方案是简单地 await那:

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()
{
// ...
}

并考虑重命名ExecuteRequestExecuteRequestAsync ,也是。

当然你必须改变method的使用里面GenericMethodAsync现在相应地:

var response = await method(request);

关于c# - 将泛型方法转换为异步导致泛型参数出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51299763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com