假设我有一个方法,它调用另一个方法,该方法接受一个字符串并返回一个字符串。这个过程会一遍又一遍地进行,直到满足某个条件:
public string RetryUntil(
Func<string, string> method,
string input,
Func<string, bool> condition,
TimeSpan timeSpan)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
string response = string.Empty;
bool conditionResult = false;
while (stopwatch.Elapsed < timeSpan && conditionResult != true)
{
result = method(input);
conditionResult = condition(result);
Thread.Sleep(TimeSpan.FromSeconds(0.5));
}
return response;
}
我觉得应该可以将“method”和“input”参数指定为一个参数。因此,我想重构它,这样我就可以像这样调用它:
RetryUntil(
ConvertString("hello World"),
(str) => { return str == "whatever"; },
TimeSpan.FromSeconds(10));
但是显然,这将传递调用ConvertString方法的结果(而不仅仅是该方法的委托)到Retry方法中。有没有一种方法可以将委托和那些委托的特定参数一起传递?我是否在反向思考整个问题?现在我做的方式感觉有点不太优雅。