如果条件不满足,有没有办法让函数重复自己

时间:2013-05-10 14:20:18

标签: c# if-statement

我有这样的事情:

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#的新手。

我怎样才能正确地制作这样的东西?

5 个答案:

答案 0 :(得分:2)

你正在寻找一个循环

while(somethingNotMet){
    //do something
    somthingNotMet=false;
}

答案 1 :(得分:0)

您正在寻找的是do while循环!

int attempts = 0;

do
{
     hasWorked = someFunction();
     attempts ++;
}
while(!hasWorked && attempts <= 1)

虽然(笑)我在这里,我想我会告诉你另一种类型的循环,称为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

答案 2 :(得分:0)

如果你真的想在不使用循环的情况下这样做,你可以使用一个可选参数并递归调用函数:

private void myfunction(int recursiveCount = 0)
{
    if (recursiveCount > 1)
    {
      // give up
      return;
    }

    if (variableA == 1)
    {
      //do my stuff
      //ta daaaa
    }
    else
    {
      myFunction(++recursiveCount);
    }
}

要使用它,只需调用该函数而不提供参数:

myfunction();

答案 3 :(得分:0)

是的,你想把这个函数放在一个循环中,让函数返回一个布尔值来表明是否应该运行它

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

答案 4 :(得分:0)

如果您只想再试一次

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.
        }
    }
}