我在我的for循环中使用数组长度作为测试条件.但是如果数组中只有一个元素,我会收到"索引超出数组范围"错误.我究竟做错了什么?谢谢.
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]
}
}
Run Code Online (Sandbox Code Playgroud)
值来自textBox,用户只能输入一个值.在这种情况下,它只需要运行一次.
数组是zero-based索引,即第一个元素具有零索引.template [0]指向第一个元素.当你只有一个template[1] will refer to second element不存在的元素时,你可能会遇到out of index异常.
更改
for (int i = 0; i <= template.Length; i++)
Run Code Online (Sandbox Code Playgroud)
至
for (int i = 0; i < template.Length; i++)
Run Code Online (Sandbox Code Playgroud)