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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…