gpt4 book ai didi

C#.Net 委托(delegate)

转载 作者:行者123 更新时间:2023-11-30 16:05:58 25 4
gpt4 key购买 nike

假设我有一个方法调用另一个接受字符串并返回字符串的方法,一遍又一遍直到满足条件:

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

感觉我应该能够将“方法”和“输入”参数指定为一个参数。所以,我想重构它,这样我就可以这样调用它,例如:

RetryUntil(
ConvertString("hello World"),
(str) => { return str == "whatever"; },
TimeSpan.FromSeconds(10));

但显然,这会将调用 ConvertString 方法的结果(而不仅仅是该方法的委托(delegate))传递给 Retry 方法。有没有办法将委托(delegate)和这些委托(delegate)的特定参数作为一个传递?我在倒着思考整个问题吗?我现在这样做的方式感觉有点不雅。

最佳答案

您正在寻找的东西通常称为“currying”,并且在 C# 中不直接支持,或者至少不如在 F# 中支持。这是一个功能,您可以在其中指定函数的一些参数,并获得一个接受剩余参数(如果有)并返回适当值的委托(delegate)。

最简单的引用方式如下:

public string RetryUntil(
Func<string> method,
Func<string, bool> condition,
TimeSpan timeSpan)

然后调用

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

=> 创建一个 lambda,它将返回给定函数的结果。由于您现在正在声明一个方法调用,因此您可以传入任何您想要的参数,或者让 lambda 本身接受一些参数,从而柯里化(Currying)参数。

关于C#.Net 委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32891564/

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