检查 while 循环是否在 C# 中的第一次迭代中

本文关键字:第一次 迭代 while 循环 是否 检查 | 更新日期: 2023-09-27 18:30:50

如何检查它是否是 C# 中while loop中的第一次迭代?

while (myCondition)
{
   if(first iteration)
     {
       //Do Somthin
     }
   //The rest of the codes
}

检查 while 循环是否在 C# 中的第一次迭代中

bool firstIteration = true;
while (myCondition)
{
   if(firstIteration )
     {
       //Do Somthin
       firstIteration = false;
     }
   //The rest of the codes
}

您可以将 do 某些事情移出循环。只有在"做 Somthin"不改变myCondition的情况下,才能保证做完全相同的事情。而且myCondition测试是纯粹的,即没有副作用。

if (myCondition)
{
  //Do Somthin
}
while (myCondition)
{
   //The rest of the codes
}

使用计数器:

int index = 0;
while(myCondition)
{
   if(index == 0) {
      // Do something
   }
   index++;
}

你可以在循环外做一个布尔值

 bool isFirst = true;
 while (myCondition)
 {
    if(isFirst)
      {
         isFirst = false;
        //Do Somthin
      }
    //The rest of the codes
 }

像这样的东西?

var first=true;
while (myCondition)
{
   if(first)
     {
       //Do Somthin
     }
   //The rest of the codes
first=false
}

定义一个布尔变量:

bool firstTime = true;
while (myCondition)
{
   if(firstTime)
     {
         //Do Somthin
         firstTime = false;
     }
   //The rest of the codes
}

您可以通过解决方法来做到这一点,例如:

boolean first = true;
    while (condition) 
    {
        if (first) {
            //your stuff
            first = false;
        }
    }

尝试这样的事情:

bool firstIteration = true;
while (myCondition)
{
   if(firstIteration)
     {
       //Do Something
       firstIteration = false;
     }
   //The rest of the codes
}

我建议为此使用计数器变量或 for 循环。

例如

int i = 0;
while (myCondition)
{
   if(i == 0)
     {
       //Do Something
     }
i++;
   //The rest of the codes
}

仍在学习,但这种方式来到了我身边,在我自己之前没有使用过这个,但我计划在我的项目中进行测试并可能实现:

int invCheck = 1;
if (invCheck > 0)
    {
        PathMainSouth(); //Link to somewhere
    }
    else
    {
        ContinueOtherPath(); //Link to a different path
    }
    static void PathMainSouth()
    {
        // do stuff here
    }
    static void ContinueOtherPath()
    {
        //do stuff
    }