Index was out of range. Must be non-negative and less than the size of the collection??

匿名 (未验证) 提交于 2019-12-03 02:42:02

问题:

im doing this simple for and i get this error. When i change TRUE to FALSE it doesnt give that error, but the test real error... but i need the test to pass and i dont understand.. can anybody help? C# visual studio 2010 NUnit

[Test]  public void prueba1() {      List<int> lista1 = new List<int>();      lista1.Add(1);      lista1.Add(2);      lista1.Add(3);      for (int i = 0; i < lista1.Count; i++)     {          Console.WriteLine(lista1[i]);         Assert.True(lista1[i]<lista1[i+1]);      } 

回答1:

The valid indexes into your list are 0 through 2.lista1.Count will be 3, so i goes from 0 to 2. When i is 2, you try to access lista1[i+1], which is out of range.



回答2:

Your list is [1,2,3]

In each iteration, the following statements are being checked.
1 < 2
2 < 3
3 < ?

In Assert.True and Assert.False, an AssertFailedException error will be throw if the conditional being checked is not the same as the function call.(Assert.True needs True)

Assert.True(1 < 2) is valid,
Assert.True(2 < 3) is valid, Assert.True(3 < ?) - An Out Of Bounds Exception will occur.

Assert.False(1 < 2) - An AssertFailedException will occur.



回答3:

i+1 is the place of error. Change it. Why?

Your indexes should start from 0 and go till 2 but error comes in the last index because it tries to search for i + 1 index which means it is searching for lista1[3] which does not exist as indexes start from 0 and go till 1 less than the length of collection.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!