Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

C# equivalent to C++ Functor (as a break condition)

I have the following example code:

void Foo()
{   
    while (!_cancelSrc.Token.IsCancellationRequested && currTryNum < maxRetryTimes && !isPublished)
    {
        // do something 
    }
}

I want to change the while condition, and pass Foo something equivalent to C++ Functor, that will hold an internal state in order to keep track of currTryNum and isPublish variables. I will define in each what is the maxRetryTimes. something like this:

while (!_cancelSrc.Token.IsCancellationRequested && isRequireToContinue())
{
    // do something 
}

P.S. It is important to also allow some functor that always returns true, in case I want the while to always run. tnx!

question from:https://stackoverflow.com/questions/65865280/c-sharp-equivalent-to-c-functor-as-a-break-condition

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In C# you have delegates to pass around methods. You can use an anonymous method that "closes" around a currTryNum variable, or you can create a whole class that has currTryNum as a property. No difference for the method receiving the delegate (and if you take a look at the generated code, the anonymous method that closes around some variables WILL be converted to an hidden class much like Tester)

void Foo(Func<bool> predicate)
{   
    while (!_cancelSrc.Token.IsCancellationRequested && predicate())
    {
        // do something 
    }
}

Now you could:

int currTryNum = 0;
int maxRetryTimes = 1000;
bool isPublished = false;

Foo(() => currTryNum++ < maxRetryTimes && !isPublished);

or you could

public class Tester
{
    public int CurrTryNum { get; set; } = 0;
    public int MaxRetryTimes = 1000;
    public bool isPublished = false;
    
    public bool Check()
    {
        return currTryNum++ < maxRetryTimes && !isPublished;
    }
}    

and then

var tester = new Tester();
Foo(tester.Check);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...