C#.Net委托

3

假设我有一个方法,它调用另一个方法,该方法接受一个字符串并返回一个字符串。这个过程会一遍又一遍地进行,直到满足某个条件:

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方法中。有没有一种方法可以将委托和那些委托的特定参数一起传递?我是否在反向思考整个问题?现在我做的方式感觉有点不太优雅。

1个回答

3
你所需要的功能通常称为“柯里化”,在C#中并没有直接支持,至少不像在F#中那样好。这是一种特性,可以指定函数的一些参数,获取一个委托,该委托接受剩余的参数(如果有的话)并返回适当的值。
最简单的引用方式如下:
public string RetryUntil(
    Func<string> method,
    Func<string, bool> condition,
    TimeSpan timeSpan)

然后通过调用

RetryUntil(
    () => ConvertString("Hello World!"),
    // ...

=> 创建一个 lambda 函数,该函数将返回给定函数的结果。由于您现在正在声明一个方法调用,因此可以传递任何参数,或者使 lambda 自身接受一些参数,从而对参数进行柯里化。


太好了,谢谢。简单的解决方案,感谢您提供“柯里化”这个术语,这对我来说是新的! - John Darvill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接