【发布时间】:2019-02-01 01:53:21
【问题描述】:
例如,我有以下方法:
private async Task<T> Read<T>(string id, string endpoint)
{
//....
}
private async Task<List<T>> List<T>(int start, int count, string endpoint, List<FilterData> filterData = null)
{
//....
}
(以及更多具有不同属性的内容)
但是所有这些方法都可以抛出BillComInvalidSessionException
如果我调用的方法抛出了这个异常,我想执行一些逻辑并调用调用的方法。
即:
private async Task<T> ReadWithRetry<T>(string id, string endpoint)
{
try
{
return await Read<T>(id, endpoint);
}
catch (BillComInvalidSessionException)
{
SessionId = new Lazy<string>(() => LoginAsync().Result);
return await ReadWithRetry<T>(id, endpoint);
}
}
private async Task<List<T>> ListWithRetry<T>(int start, int count, string endpoint, List<FilterData> filterData = null)
{
try
{
return await List<T>(start, count, endpoint, filterData);
}
catch (BillComInvalidSessionException)
{
SessionId = new Lazy<string>(() => LoginAsync().Result);
return await ListWithRetry<T>(start, count, endpoint, filterData);
}
}
如何创建一个通用方法,执行相同的逻辑,但获取不同的方法作为参数?
【问题讨论】:
-
我不知道你会怎么做,也许如果你改变每个方法来获取一个对象数组,它们都会有相同的签名,但你会装箱/拆箱参数一直,并且必须进行所有验证检查,以确保每个都是正确的类型,所以我不知道这是否比仅仅做你所拥有的工作更多或更少。
-
@Neil.Work 现在我有“复制/粘贴”代码。看来,我可以用 Func<...> 实现它,但不明白该怎么做:)