2012-09-15 128 views
0

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

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);  
    } 

回答

0

您需要一个更大的阵列。

第二个循环的很清楚的边界之外写入,相关细节:

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

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

1

你得到这个错误,因为你的矩形[]数组的大小比10小的。请记住,当你宣布你的矩形[]数组,你至少应该有一个大小为10

声明它
Rectangle[] sourceRects = new Rectangle[10]; //(it will be from 0 to 9) 

然后,您将能够为其添加10个矩形。

1

你犯了2个错误(失去调整大小,第二个失败)。 看看我修改后的代码:

private void vorrück(ref 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); 
     } 
     Array.Resize(ref sourceRects, doublelenght); 
     for (int normallenght = sourceRects.Length /2; normallenght < doublelenght; normallenght++) 
     { 
      sourceRects[normallenght] = new Rectangle((sourceRects.Length - 1 - normallenght) * framewidth, 0, framewidth, frameheight); 
     } 
    } 

此代码将调整,并填写您的sourceRects阵列。

您可以使用此代码:

 Rectangle[] sourceRects = new Rectangle[2]; 
     vorrück(ref sourceRects,5,4); 
相关问题