2012-12-11 3 views
1

for 루프에서 테스트 조건으로 배열 길이를 사용하고 있습니다. 그러나 배열에 요소가 하나만 있으면 '인덱스가 배열의 경계를 벗어났습니다.'오류가 발생합니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까? 감사.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] 
    } 
} 

값이 textBox에서 오는 경우 사용자는 하나의 값만 입력 할 수 있습니다. 어떤 경우에는 한 번만 실행하면됩니다.

+0

당신은 아마 더 나은 제공 될 것입니다 ... 사용해야합니다 /ttw7t8t6.aspx). 색인 수학은 실제로 C#에서 시간 낭비입니다. –

답변

5

배열은 zero-based 색인, 즉 첫 번째 요소는 0 색인입니다. template [0]은 첫 번째 요소를 가리 킵니다. template[1] will refer to second element 요소가 하나만있는 경우에는 out of index 예외가 발생합니다.

변경

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

0에서

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

카운트 시작하려면, 당신은에 문을 위해 먼저 변경해야 ...

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

가 사용

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

... 마지막 반복에서 itemplate.Length과 같습니다. template[template.Length]은 항상 IndexOutOfRangeException이됩니다. template의 마지막 요소가 실제로 인덱스 template.Length - 1을 가지고 있기 때문에, 대신 http://msdn.microsoft.com/en-us/library ([foreach 문]을 사용하여

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