繁体   English   中英

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

[英]Check if while loop is in first iteration in C#

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

while (myCondition)
{
   if(first iteration)
     {
       //Do Somthin
     }

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

   //The rest of the codes
}

你可以将 do something 移出循环。 只有在“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++;
}

像这样的东西?

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
}

你可以在循环外做一个 bool

 bool isFirst = true;
 while (myCondition)
 {
    if(isFirst)
      {
         isFirst = false;
        //Do Somthin
      }
    //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
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM