【问题标题】:Index was out of range. Must be non-negative and less than the size of the collection??指数超出范围。必须是非负数且小于集合的大小??
【发布时间】:2012-05-15 14:05:58
【问题描述】:

我这样做很简单,但我得到了这个错误。当我将 TRUE 更改为 FALSE 时,它不会给出该错误,但测试是真正的错误......但我需要通过测试,但我不明白......有人可以帮忙吗? 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]);

    }

【问题讨论】:

    标签: c# indexing nunit


    【解决方案1】:

    列表中的有效索引是 0 到 2。lista1.Count 将为 3,因此 i 从 0 变为 2。当 i 为 2 时,您尝试访问 lista1[i+1],它超出了范围。

    【讨论】:

      【解决方案2】:

      您的列表是 [1,2,3]

      在每次迭代中,都会检查以下语句。
      1 2 3

      在Assert.True和Assert.False中,如果被检查的条件与函数调用不同,则会抛出AssertFailedException错误。(Assert.True需要True)

      Assert.True(1 Assert.True(2

      Assert.False(1

      【讨论】:

        【解决方案3】:

        i+1 是错误的地方。更改。为什么?

        您的索引应该从 0 开始一直到 2,但最后一个索引出现错误,因为它尝试搜索 i + 1 索引,这意味着它正在搜索不存在的 lista1[3],因为索引从 0 开始并继续直到比集合长度少 1。

        【讨论】:

          猜你喜欢
          • 2012-02-11
          • 1970-01-01
          相关资源
          最近更新 更多