是否有一种方法,让一个函数重复自己,如果一个条件不满足
本文关键字:一个 自己 条件 如果 不满足 一种 方法 是否 函数 | 更新日期: 2023-09-27 18:12:56
我有这样的东西:
static int cantryagain=0;
private void myfunction(){
if (cantryagain==0)
{
if(variableA=1)
{
//do my stuff
//ta daaaa
}
else
{
//do something magical that will help make variableA=1 but
//if the magic doesnt work i only want it to try once.
tryagain();
}
}
}
private void tryagain
{
myfunction();
cantryagain=1; //to make sure the magic only happens once, but
//obviously it never gets here as it does
//myfunction again before it ever can...
}
我知道这段代码很蹩脚。我对c#相当陌生。
我怎样才能正确地做出这样的东西呢?
你正在寻找一个循环
while(somethingNotMet){
//do something
somthingNotMet=false;
}
如果真的不想使用循环,可以使用可选形参并递归地调用该函数:
private void myfunction(int recursiveCount = 0)
{
if (recursiveCount > 1)
{
// give up
return;
}
if (variableA == 1)
{
//do my stuff
//ta daaaa
}
else
{
myFunction(++recursiveCount);
}
}
要使用它,只需调用函数而不提供参数:
myfunction();
如果你只想再试一次
static int cantryagain=0;
private void myfunction()
{
for (int i = 0; i < 2; i++) // will loop a max of 2 times
{
if(variableA=1)
{
//do my stuff
//ta daaaa
break; //Breaks out of the for loop so you don't loop a second time
}
else if (i == 0) // Don't bother if this isn't the first iteration
{
//do something magical that will help make variableA=1 but
//if the magic doesnt work i only want it to try once.
}
}
}
是的,你想把函数放在一个循环中,并让函数返回一个布尔值,指示是否应该运行
private bool myFunction() {
Random random = new Random();
return random.Next(0, 100) % 2 == 0; // return true or false, this would be your logic to implement
}
public bool doSomething() {
var tryAgain = false;
do {
tryAgain = myFunction(); // when myFunction returns false, the loop condition isn't met, and the loop will exit
} while (tryAgain);
}
你正在寻找的是所谓的do while
循环!
int attempts = 0;
do
{
hasWorked = someFunction();
attempts ++;
}
while(!hasWorked && attempts <= 1)
虽然(lol)我在这里,我想我给你看另一种类型的循环,称为For
循环。当你知道你的代码要运行多少次时,使用这种类型的循环。
for(int x = 0; x < 10; x++)
{
Console.Writeline("Hello there number : " + X);
}
这将打印出:
Hello there number 0
Hello there number 1
Hello there number 2
...
Hello there number 9