[英]How to save data of two for loops in one array?
我有两个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);
}
您得到此错误是因为Rectangle []数组的大小小于10.请记住,当您声明Rectangle []数组时,至少应该声明它的大小为10。
Rectangle[] sourceRects = new Rectangle[10]; //(it will be from 0 to 9)
然后,您将能够为其添加10个矩形。
你犯了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);
你需要一个更大的阵列。
第二个循环非常清楚地写在界外,相关的细节是:
for (int normallenght = sourceRects.Length; ...; ...)
sourceRects[normallenght] = ...; // normallenght >= sourceRects.Length
作为一般解决方案,不要使用如此多的数组。 在这种情况下, List<Rectangle>
可能是首选的数据结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.