2012-12-11 30 views
1

我在我的for循环中使用数组长度作为测试条件。但是,如果数组中只有一个元素,我会收到'索引超出数组范围'的错误。我究竟做错了什么?谢谢。数组有1个元素导致循环中的错误

string templateList; 
string[] template; 

string sizeList; 
string[] size; 

templateList = textBox1.Text; 
template = templateList.Split(','); 

sizeList = textBox2.Text;    
size = sizeList.Split(','); 

for (int i = 0; i <= template.Length; i++) 
{ 
    for (int j = 0; j < size.Length; j++) 
    { 
     //do something with template[i] and size[j] 
    } 
} 

这些值来自文本框,用户只能输入一个值。在这种情况下,它只需要运行一次。

+0

你可能会得到更好的服务使用[的foreach(http://msdn.microsoft.com/en-us/library /ttw7t8t6.aspx)。索引数学在C#中真的浪费时间。 –

回答

5

数组是zero-based索引,即第一个元素具有零索引。模板[0]指向第一个元素。当你只有一个元素template[1] will refer to second element这是不存在的,你可能会得到out of index异常。

变化

for (int i = 0; i <= template.Length; i++) 

从零

for (int i = 0; i < template.Length; i++) 
0

计数开始,你必须改变你的第一个for语句为:

for (int i = 0; i < template.Length; i++) {....} 
1

使用...

for (int i = 0; i <= template.Length; i++) 

...最后一次迭代i将等于template.Lengthtemplate[template.Length]将始终导致IndexOutOfRangeException。由于template最后一个元素实际上有指数template.Length - 1,你应该使用...

for (int i = 0; i < template.Length; i++) 
相关问题