Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C相当于C++;函子(作为中断条件)_C# - Fatal编程技术网

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