异步方法返回任务&LT; T&GT;在C#泛型约束 [英] Async method returning Task<T> with generic constraint in C#
问题描述
我实现了在一个项目,我的工作。这是pretty目前大部分结构:
I've implemented a command pattern in a project I'm working on. This is pretty much the current structure:
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改变这样的事情...
I want to handle any exceptions that could be thrown by the HttpClient, so I want to change CommandBase.ExecuteAsync to something like this...
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
}
}
编译错误我得到的是无法将响应式异步返回类型T。我不能使用 T.CreateErrorResponse()
,所概述<一href=\"http://stackoverflow.com/questions/196661/calling-a-static-method-on-a-generic-type-parameter\">in这个问题。
我如何解决此问题?
编辑downvoters:你是否与在这样的图书馆捕获异常同意,问题仍然有效。
Edit to downvoters: whether or not you agree with catching exceptions in a library like this, the question still stands!
推荐答案
虽然我不知道这是最好的解决办法(或在您的特定使用案例可行的),你可以做的是:
Although I am not sure this is the best solution (or feasible in your specific use case), what you can do is:
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;
}
}
用法:
catch (HttpRequestException hex)
{
return Response.CreateErrorResponse<T>(ExceptionDispatchInfo.Capture(hex)); // should compile (I did not check)
}
这篇关于异步方法返回任务&LT; T&GT;在C#泛型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!