【问题标题】:C# When using foreach on a list of arrays, the foreach only iterates 5 times even though the list has length 86C# 在数组列表上使用 foreach 时,即使列表长度为 86,foreach 也仅迭代 5 次
【发布时间】:2016-01-27 22:31:24
【问题描述】:

我正在用 C# 编写一个国际象棋引擎,并且我正在尝试调试移动生成。到目前为止,我一直在使用断点来检查变量,但我需要一种更好的调试方法。尽管断点显示此列表的长度为 86,但循环仅运行 5 次。我唯一能想到的是列表中的数组长度为 5,但我不知道是什么原因造成的。

foreach (int[] debugBoard in futures)
{

    for (int i = 0; i < 5; i++)
    {
        Debug.Write(debugBoard[i].ToString().PadLeft(3, ' '));
    }
    Debug.Write("\n");
    int[,] debugOutBoard = new int[8, 8];
    Array.Copy(chessBoard.Pieces(), debugOutBoard, 64);

    if (debugBoard[0] < 0 || debugBoard[1] < 0 || debugBoard[2] < 0 || debugBoard[3] < 0 || debugBoard[0] > 7 || debugBoard[1] > 7 || debugBoard[2] > 7 || debugBoard[3] > 7) 
        break;

    debugOutBoard[debugBoard[2], debugBoard[3]] = debugOutBoard[debugBoard[0], debugBoard[1]];
    debugOutBoard[debugBoard[0], debugBoard[1]] = 0;
    int rowLength = debugOutBoard.GetLength(0);
    int colLength = debugOutBoard.GetLength(1);

    for (int i = 0; i < rowLength; i++)
    {
        for (int j = 0; j < colLength; j++)
        {
            Debug.Write(debugOutBoard[i, j].ToString().PadLeft(3, ' '));
        }
        Debug.Write(Environment.NewLine + Environment.NewLine);
    }
}

另外,我尝试使用并发包来存储移动(稍后我将多线程处理移动处理),但是一旦 foreach 循环接触到并发包,包的所有内存值都变为一个值。我已经被这个障碍卡住了好几天了,我真的需要帮助。

【问题讨论】:

  • 那个 if 语句打破了你的 foreach 循环......我会写一个答案,但我不知道 if 实际试图完成什么
  • 啊,很好的收获。我相信这可能就是问题所在。我的意思是迭代到下一个元素。我会使用什么命令来做到这一点?
  • 我添加了一个答案(使用continue)

标签: c# arrays multithreading list chess


【解决方案1】:

当满足条件时,您的 if 语句会跳出 for 循环,我认为这是第 5 次/第 6 次迭代时第一次发生。

我的意思是迭代到下一个元素。我会使用什么命令来做到这一点? ——

您需要使用continue 而不是break

【讨论】:

    【解决方案2】:

    如果 'futures' 包含 86 个项目,它可以停止迭代的唯一方法是发生异常。除非您在某处处理异常,否则 Visual Studio(在默认设置中)应该会在发生这种情况时中断。

    将整个事情包装在一个 try{} catch{} 中,并在 catch 中设置一个断点,看看它是否命中。

    【讨论】:

    • 不,断点不会触发。我唯一能想到的是它使用的是数组长度,但我仍在从列表中提取数据。
    • 啊,我没有休息;看看其他答案
    猜你喜欢
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多