double breite = new double();
breite = Application.Current.Host.Content.ActualWidth - 20;
rectA = new Rectangle();
rectA.Width = breite;
rectA.Height = 200;
rectA.Fill = greY;
Rectangle[] smallRect = new Rectangle[16];
for (int i = 0; i < (breite)-20; i++) {
smallRect[i] = new Rectangle();
smallRect[i].Width = 100;
smallRect[i].Height = 100;
}
Content.Children.Add(progBar);
Box.Children.Add(rectA);
Box.Children.Add(smallRect[16]);
此代码适用于Windows Phone 8.0应用程序。总有一个System.IndexOutOfRangeException,但我不知道为什么。
对不起这个问题,但我已经搜索了很多,但还没有找到答案。我知道这对你来说是一个非常简单的问题,但我是C#的新手。
这是它的截图 https://dl.dropboxusercontent.com/u/51974164/public/Code5.JPG
答案 0 :(得分:1)
您的循环索引应该可能取决于您循环的集合。在这种情况下,我们有一个Rectangle
长度为16的数组(最大数组索引为15),但是你是否正在循环看似像素?尝试更改循环逻辑以转到smallRect
数组的上限。
Rectangle[] smallRect = new Rectangle[16];
for (int i = 0; i < smallRect.Length; i++) {
smallRect[i] = new Rectangle();
smallRect[i].Width = 100;
smallRect[i].Height = 100;
}
上述应该有效,但是,我不确定你要完成什么。
我还在最后一行注意到你试图访问未定义的smallRect[16]
,因为最大数组索引是15(因为长度是16)。如果您只想要smallRect
数组中的最后一个条目,请考虑使用smallRect.Last()
。
答案 1 :(得分:0)
您正在制作一个包含16个广告位的新阵列:
Rectangle[] smallRect = new Rectangle[16];
你可以做的最长的for循环是:
for (int i = 0; i < 16; i++) { }
(breite)-20
大于16,这就是你的循环给出System.IndexOutOfRangeException
- 错误的原因。
答案 2 :(得分:0)
我知道这是一个老问题,但是对于那些来自 Java 等其他语言的人来说,一个潜在的问题是当您迭代多维数组时!
// 2 dimensional array of strings
string [,] matrix = new string[,] {
{ "Hello", "Goodbye" },
{ "Foo", "Bar" }
};
// WONT work (Length is the number of elements in the entire matrix, not just
// the number of rows)
for (var i = 0; i < matrix.Length; i++) {
Console.WriteLine("Key: " + matrix[i][0]);
}
// this WILL work (you are requesting the length now of only 1 dimension: the # of
// rows)
for (var i = 0; i < matrix.GetLength(0); i++) {
Console.WriteLine("Key: " + matrix[i][0]);
}
如果您想一次只迭代 1 个维度,请改用 Array.GetLength。