修复委托的“方法组”问题

时间:2013-05-04 15:27:20

标签: c# delegates

灵感来自Cleanest way to write retry logic?我做了这个

    public static T Retry<T>(int numRetries, int timeout, Delegate method, params object[] args)
    {
        if (method == null)
            throw new ArgumentNullException("method");

        var retval = default(T);
        do
        {
            try
            {
                retval = (T) method.DynamicInvoke(args);
                return retval;
            }
            catch (TimeoutException)
            {
                if (numRetries <= 0)
                    throw; // avoid silent failure
                Thread.Sleep(timeout);
            }
        } while (numRetries-- > 0);

        return retval;
    }

但是我遇到了method group问题。

测试设置

    private int Add(int x, int y)
    {
        return x + y;
    }

    public static void Main(string[] args)
    {
        var r = Retry<int>(5, 10, Add, 1, 1);
    }

除了Retry<int>(5, 10, new Func<int, int, int>(Add), 1, 1);

之外,还有其他方法可以解决这个问题

1 个答案:

答案 0 :(得分:4)

您可以将Retry更改为

public static T Retry<T>(int numRetries, int timeout, Func<T> method)
{
    if (method == null)
        throw new ArgumentNullException("method");

    var retval = default(T);
    do
    {
        try
        {
            retval = method();
            return retval;
        }
        catch (TimeoutException)
        {
            if (numRetries <= 0)
                throw; // avoid silent failure
            Thread.Sleep(timeout);
        }
    } while (numRetries-- > 0);

    return retval;
}

并致电

var result = Retry(5, 10, ()=>Add(1,1));