0

我有这样的事情:

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# 还很陌生。

我怎么能正确地做出这样的事情?

4

5 回答 5

2

你正在寻找一个循环

while(somethingNotMet){
    //do something
    somthingNotMet=false;
}
于 2013-05-10T14:22:26.260 回答
1

如果您真的想在不使用循环的情况下执行此操作,则可以使用可选参数并递归调用该函数:

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

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

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

myfunction();

于 2013-05-10T14:24:01.083 回答
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
于 2013-05-10T14:22:34.060 回答
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);
  }
于 2013-05-10T14:25:33.187 回答
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.
        }
    }
}
于 2013-05-10T14:38:59.520 回答