C# C相当于C++;函子(作为中断条件)
我有以下示例代码:C# C相当于C++;函子(作为中断条件),c#,C#,我有以下示例代码: void Foo() { while (!_cancelSrc.Token.IsCancellationRequested && currTryNum < maxRetryTimes && !isPublished) { // do something } } 另外,如果我想让while始终运行,那么允许某些始终返回true的函子也很重要。 tnx 在C#中,您有代理来传递方法。您可以使用
void Foo()
{
while (!_cancelSrc.Token.IsCancellationRequested && currTryNum < maxRetryTimes && !isPublished)
{
// do something
}
}
另外,如果我想让while始终运行,那么允许某些始终返回true的函子也很重要。
tnx 在C#中,您有代理来传递方法。您可以使用围绕currTryNum
变量“关闭”的匿名方法,也可以创建将currTryNum
作为属性的整个类。接收委托的方法没有区别(如果您查看生成的代码,关闭某些变量的匿名方法将转换为隐藏类,非常类似于Tester
)
在计数器周围关闭一个匿名方法就足够了。然后将此匿名方法的委托传递给
Foo
方法。
while (!_cancelSrc.Token.IsCancellationRequested && isRequireToContinue())
{
// do something
}
void Foo(Func<bool> predicate)
{
while (!_cancelSrc.Token.IsCancellationRequested && predicate())
{
// do something
}
}
int currTryNum = 0;
int maxRetryTimes = 1000;
bool isPublished = false;
Foo(() => currTryNum++ < maxRetryTimes && !isPublished);
public class Tester
{
public int CurrTryNum { get; set; } = 0;
public int MaxRetryTimes = 1000;
public bool isPublished = false;
public bool Check()
{
return currTryNum++ < maxRetryTimes && !isPublished;
}
}
var tester = new Tester();
Foo(tester.Check);