首页 > 解决方案 > 在 FORWARD for 循环中向后移动

问题描述

我不确定如何解释这一点,也无法在任何地方找到答案。我有一个 for 循环,它遍历通过字符串表示的行。

for (int i = 0; i < dataLines.Length; i++)
{

    jumpPoint:
        Debug.Log("Jumped");

    string[] words = dataLines[i].Split();
    .
    .               
    . "words[] manipulation and reading"
    .
    .
}

我的任何数据处理或循环中发生的事情都没有问题。但是我有一个实例,我需要转到上一个dataLine[]并从该点继续(也重新运行自该点以来已经运行的代码)。

我所做的基本上归结为

i = ?; //arbitrary number for the situation that is definitely not out of bounds for the loop
goto jumpPoint;

我也尝试过不使用跳转点,也只是在重置 for 循环索引后让循环循环到下一个。

我知道跳转点不是问题,因为它用于不相关的事情并且跳转工作正常。另外值得一提的是,在这些情况下,我正在增加i索引,因此 for 循环过早地推进并且效果很好。

那么为什么我不能在循环中倒退呢?这只是不可能的事情吗?

标签: c#loopsfor-loopunity3d

解决方案


没有什么能阻止你在循环中倒退。你可以控制你的代码逻辑,所以你所要做的就是当你的“jumpPoint”条件满足时,只需将迭代器改i回你想要的前一个值。

例如:假设我想跳回并重新运行某些内容,因为其中包含“jump”一词。

Console.WriteLine("App started.");
List<string> dataLines = new List<string>() { "this is a phrase", "This is another but with jump in it", "this is the last" };
bool alreadyJumped = false;
for (int i = 0; i < dataLines.Count; i++)
{
    Console.WriteLine($"Currently Iterating: {i}");
    string[] words = dataLines[i].Split();
    Console.WriteLine($"Do some with this data: {dataLines[i]}");
    if (words.Contains("jump") && !alreadyJumped)
    {
        alreadyJumped = true;

        // Reset the i value so that the next iteration will run again.
        i = i - 1;
    }
    else if (alreadyJumped)
    {
        // Once 
        alreadyJumped = false;
    }

}
Console.WriteLine("App done.");

这将产生以下输出:

App started.
Currently Iterating: 0
Do some with this data: this is a phrase
Currently Iterating: 1
Do some with this data: This is another but with jump in it
Currently Iterating: 1
Do some with this data: This is another but with jump in it
Currently Iterating: 2
Do some with this data: this is the last
App done.

推荐阅读