gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:58:03 24 4
gpt4 key购买 nike

灵感来自 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); 没有更好的方法来解决这个问题吗?

最佳答案

你可以把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));

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com