C# 中返回带有通用约束的 Task 的异步方法

2024-05-01

我已经实现了命令模式我正在做的一个项目 https://github.com/rikkit/lastfm-wp。这几乎是当前的结构:

public class Response
{
    public bool Success { get; private set; }

    public static Response CreateErrorResponse()
    {
        return new Response { Success = false };
    }
}

public interface ICommand<T> where T : Response
{
    Task<T> ExecuteAsync();
}

public abstract CommandBase : ICommand<T> where T: Response
{
    protected abstract Uri BuildUrl();
    protected abstract Task<T> HandleResponseAsync();

    public async override Task<T> ExecuteAsync()
    {
        var url = BuildUrl();
        var httpClient = new HttpClient();

        var response = await httpClient.GetAsync(url);
        return await HandleResponseAsync(response);
    }
}

我想处理 HttpClient 可能引发的任何异常,所以我想将 CommandBase.ExecuteAsync 更改为这样的内容......

public async override Task<T> ExecuteAsync()
{
    var url = BuildUrl();
    var httpClient = new HttpClient();

    try
    {
        var response = await httpClient.GetAsync(url);
        return await HandleResponseAsync(response);
    }
    catch (HttpRequestException hex)
    {
        return Response.CreateErrorResponse(); // doesn't compile
    }
}

我得到的编译错误是“无法将类型 Response 转换为异步返回类型 T”。我不能使用T.CreateErrorResponse(),如概述的在这个问题中 https://stackoverflow.com/questions/196661/calling-a-static-method-on-a-generic-type-parameter.

我该如何解决这个问题?

编辑给反对者:无论您是否同意在这样的库中捕获异常,问题仍然存在!


虽然我不确定这是最好的解决方案(或者在您的特定用例中可行),但您可以做的是:

public class Response
{
    public bool Success { get; private set; }
    public ExceptionDispatchInfo ErrorInfo { get; private set; }
    public bool HasFailed
    {
        get { return !Success; }
    }

    public static T CreateErrorResponse<T>(ExceptionDispatchInfo errorInfo) where T : Response, new()
    {
        var response = new T();
        response.Success = false;
        response.ErrorInfo = errorInfo;
        return response;
    }
}

Usage:

catch (HttpRequestException hex)
{
    return Response.CreateErrorResponse<T>(ExceptionDispatchInfo.Capture(hex)); // should compile (I did not check)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# 中返回带有通用约束的 Task 的异步方法 的相关文章

随机推荐