【问题标题】:C# : Common method/wrapper for methods with different definitionsC#:具有不同定义的方法的通用方法/包装器
【发布时间】: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<...> 实现它,但不明白该怎么做:)

标签: c# delegates func


【解决方案1】:

您可以通过使用通用委托来实现此目的:

private async Task<T> Retry<T>(Func<Task<T>> func)
{
    try
    {
        return await func();
    }
    catch (BillComInvalidSessionException)
    {
        SessionId = new Lazy<string>(() => LoginAsync().Result);
        return await Retry(func);
    }
}

然后你的重试方法会变成:

private async Task<T> ReadWithRetry<T>(string id, string endpoint)
{
    return await Retry(async () => await Read<T>(id, endpoint));
}

private async Task<List<T>> ListWithRetry<T>(int start, int count, string endpoint, List<FilterData> filterData = null)
{
    return await Retry(async () => await List<T>(start, count, endpoint, filterData));
}

【讨论】:

  • 为什么要为方法添加static
  • 我将它们设置为静态,因为我在控制台应用程序中拥有它。我刚刚删除了静态修饰符,因为它们不是必需的并且避免混淆
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 2018-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-08
  • 1970-01-01
相关资源
最近更新 更多