You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

3D数组索引越界问题求助:遍历循环触发报错

解决数组索引越界问题:嵌套循环条件错误导致的异常

兄弟,一眼就瞅出问题所在了——你的嵌套循环里的判断条件全写错了!

仔细看你的循环代码:

  • 第二层循环是用来遍历数组第二维度的j,但你写的终止条件是i < posAr_ItemManager.GetLength(1),这完全不对,应该是j < posAr_ItemManager.GetLength(1)
  • 第三层循环遍历第三维度的z,终止条件居然也是i < posAr_ItemManager.GetLength(2),同样要改成z < posAr_ItemManager.GetLength(2)

这种错误会导致j和z不受数组对应维度长度的限制,一直递增直到超出数组的索引范围,直接触发索引越界异常。

给你修正后的完整代码:

for (int i = 0; i < posAr_ItemManager.GetLength(0); i++) 
{ 
    for (int j = 0; j < posAr_ItemManager.GetLength(1); j++) 
    { 
        for (int z = 0; z < posAr_ItemManager.GetLength(2); z++) 
        { 
            if (posAr_ItemManager[i,j,z] != null) 
            { 
                Button but = posAr_ItemManager[i, j, z]; 
                but.Width = itemWidth; 
                but.Height = itemHeight; 
                but.SetValue(Canvas.LeftProperty, itemPanelX + (i + 1) * butSpacing + i * itemWidth); 
                // 顺便提一句:如果i对应列、j对应行的话,Top属性应该用j计算,不然布局会乱
                but.SetValue(Canvas.TopProperty, itemPanelY + (j + 1)*butSpacing + j* itemHeight); 
            } 
        } 
    } 
}

另外多说一句:你原来的Top属性计算用的是i,如果i是数组的行维度、j是列维度,那这里应该换成j才对,不然所有控件都会堆在同一垂直位置,肯定不符合你的布局预期。

内容的提问来源于stack exchange,提问作者cooldanietje

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:53:50