c# - 修复委托(delegate)的 'method group' 问题

标签 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); 之外,还有没有更好的方法来解决这个问题?

最佳答案

您可以将重试更改为

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));

关于c# - 修复委托(delegate)的 'method group' 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16375901/

相关文章:

c# - MemberExpression 在不应该返回 null 的情况下强制返回 null

c# - 如何在 C# 中将项目从一个列表移动到另一个列表?

c# - 如何从 C# 中的显示名称获取 Active Directory 中的用户名?

C# 匿名委托(delegate)效率/安全

c# - 在 C# 中异步运行多个委托(delegate)并等待响应

qt - 如果我想使用 Qt 中的对话框编辑项目,我应该使用委托(delegate)类吗?

objective-c - 为什么我的 NSApplicationDelegate 类中的 applicationWillFinishLaunching 从未被调用?

C# Linq 查询帮助删除 foreach 循环创建更清晰的代码

javascript - 从 JSON 响应创建一个可观察的敲除数组

c# - 使用 configSource 转换包含的配置文件