我在我的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]
}
}
这些值来自文本框,用户只能输入一个值。在这种情况下,它只需要运行一次。
你可能会得到更好的服务使用[的foreach(http://msdn.microsoft.com/en-us/library /ttw7t8t6.aspx)。索引数学在C#中真的浪费时间。 –