查找棋子位置时列索引直接跳至11的问题排查求助
问题排查:嵌套循环中列变量异常跳变的原因
核心问题1:内层break无法终止外层循环
当找到匹配newPosition的元素时,你用break只跳出了内层的r循环,但外层的c循环会继续执行,直到c达到gameBoardProperties.GetLength(0)的上限(也就是你看到的11,说明数组第一维度的长度是11)。最后返回的col会是外层循环结束时的c值,而非找到匹配项时的正确值。
核心问题2:二维数组维度遍历可能混淆
C#中二维数组的GetLength(n)规则:
GetLength(0)返回**第一维度(行)**的长度GetLength(1)返回**第二维度(列)**的长度
你当前用c遍历第一维度、r遍历第二维度,最后将c赋值给col、r赋值给row,这可能和你实际的行列定义搞反,导致后续Grid控件的行列设置出错。
修复方案
方案1:找到匹配项后直接返回(最简洁)
修改FindIndicesForPosition方法,找到目标元素后立即返回结果,避免循环继续执行:
private (int, int) FindIndicesForPosition(Property[,] gameBoardProperties, int newPosition) { for (int c = 0; c < gameBoardProperties.GetLength(0); c++) { for (int r = 0; r < gameBoardProperties.GetLength(1); r++) { if (gameBoardProperties[c, r] != null && gameBoardProperties[c, r].Position == newPosition) { // 找到后直接返回,终止所有循环 return (r, c); } } } // 未找到匹配项时返回默认值 return (-1, -1); }
方案2:用标记控制外层循环
如果需要保留后续逻辑(比如日志输出),可以用布尔标记控制外层循环的终止:
private (int, int) FindIndicesForPosition(Property[,] gameBoardProperties, int newPosition) { int row = -1, col = -1; bool isFound = false; for (int c = 0; c < gameBoardProperties.GetLength(0) && !isFound; c++) { for (int r = 0; r < gameBoardProperties.GetLength(1); r++) { if (gameBoardProperties[c, r] != null && gameBoardProperties[c, r].Position == newPosition) { row = r; col = c; isFound = true; break; } } } return (row, col); }
额外检查点
确认行列映射是否正确:如果你的gameBoardProperties是[行,列]的结构,返回的(r, c)对应(行索引, 列索引),那么后续的Grid设置代码应该是:
Grid.SetRow(player.Piece, row); Grid.SetColumn(player.Piece, col);
如果之前的行列赋值搞反,需要同步修正这部分代码。
内容的提问来源于stack exchange,提问作者artic
相关产品推荐
相关产品推荐

