首页 > c# > 如何在一个数组中保存两个for循环的数据?

如何在一个数组中保存两个for循环的数据? (How to save data of two for loops in one array?)

2012-09-15 c#xna

问题

我有两个for循环,我想将这些数据保存在一个数组中。第一个for循环将在数组中创建5个矩形。之后,第二个for循环将创建5个矩形并将它们添加到数组中。但有些东西不起作用。我在代码的最后一行得到“索引超出数组的范围”错误消​​息,我不知道要改变什么。

int framewidth = texture.Width / sourceRects.Length; 
int frameheight = texture.Height; 

private void vorrück(Rectangle[] sourceRects, int framewidth, int frameheight) 
    { 
        int doublelenght = sourceRects.Length * 2; 
        for (int i = 0; i < sourceRects.Length; i++) 
            sourceRects[i] = new Rectangle(i * framewidth, 0, framewidth, frameheight); 
        for (int normallenght = sourceRects.Length; normallenght < doublelenght; normallenght++) 
            sourceRects[normallenght] = new Rectangle((sourceRects.Length - 1 - normallenght) * framewidth, 0, framewidth, frameheight);      
    }

解决方法

你需要一个更大的阵列。

第二个循环非常清楚地写在界外,相关的细节是:

for (int normallenght = sourceRects.Length; ...; ...) 
        sourceRects[normallenght] = ...;  //  normallenght >= sourceRects.Length

作为一般解决方案,不要使用如此多的数组。在这种情况下,a List<Rectangle>可能是首选的数据结构。

问题

I have two for loops and I wanna save that data in one array. The first for loop will create 5 rectangles in the array. After that, the second for loop will create 5 rectangles and add them to the array. But something doesn't work. I get that "Index was outside the bounds of the array" error message in the last line of the code and I don't know what to change.

int framewidth = texture.Width / sourceRects.Length; 
int frameheight = texture.Height; 

private void vorrück(Rectangle[] sourceRects, int framewidth, int frameheight) 
    { 
        int doublelenght = sourceRects.Length * 2; 
        for (int i = 0; i < sourceRects.Length; i++) 
            sourceRects[i] = new Rectangle(i * framewidth, 0, framewidth, frameheight); 
        for (int normallenght = sourceRects.Length; normallenght < doublelenght; normallenght++) 
            sourceRects[normallenght] = new Rectangle((sourceRects.Length - 1 - normallenght) * framewidth, 0, framewidth, frameheight);      
    }

解决方法

You need a bigger array.

The second loop very clearly writes outside the bounds, the relevant details are:

for (int normallenght = sourceRects.Length; ...; ...) 
        sourceRects[normallenght] = ...;  //  normallenght >= sourceRects.Length

As a general solution, do not use arrays so much. In this case a List<Rectangle> is probably the preferred datastructure.

相似信息