C#将参数传递给Lambda

时间:2016-12-23 01:46:23

标签: c# lambda

在下文中,我需要将nextDB传递给Retry中的Lambda表达式:

Retry.Do(() => 
{
    string nextDB = dbList.Next();
    using (DataBaseProxy repo = new DataBaseProxy(nextDB))
    {
        return repo.DoSomething();
    }
});

我该怎么做?这是我的Retry课程:

public static class Retry
{
    public static void Do(
        Action action,
        int retryCount = 3)
    {
        Do<object>(() =>
        {
            action();
            return null;
        }, retryCount);
    }

    public static T Do<T>(
        Func<T> action,
        int retryCount = 3)
    {
        var exceptions = new List<Exception>();

        for (int retry = 0; retry < retryCount; retry++)
        {
            try
            {
                return action();
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }
        }

        throw new AggregateException(exceptions);
    }
}

1 个答案:

答案 0 :(得分:5)

我想你想在这里使用Action<T>。例如:

public static void Do<T>(
    Action<T> action,
    T param,
    int retryCount = 3)
{
    var exceptions = new List<Exception>();

    for (int retry = 0; retry < retryCount; retry++)
    {
        try
        {
            action(param);
            return;
        }
        catch (Exception ex)
        {
            exceptions.Add(ex);
        }
    }

    throw new AggregateException(exceptions);
}

您可以这样调用此函数:

Do(s => {
    Console.WriteLine(s);
}, "test", 3);

根据您的评论,您似乎希望传入多个数据库并连续尝试每个数据库,直到找到有效的数据库。一个简单的选择是删除到retryCount,然后传入您的数组。

public static void Do<T>(
    Action<T> action,
    IEnumerable<T> items)
{
    var exceptions = new List<Exception>();

    foreach(var item in items)
    {
        try
        {
            action(item);
            return;
        }
        catch (Exception ex)
        {
            exceptions.Add(ex);
        }          
    }

    throw new AggregateException(exceptions);
}

现在你称之为:

Do(s => {
    Console.WriteLine(s);
}, new[] { "db1", "db2", "db3" });