指数超出范围

时间:2016-06-14 14:44:02

标签: c#

我在getProxy()收到错误,错误是索引outofbounds。

错误:

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information:
Index was out of range. Must be non-negative and less than the size of the collection.

代码:

static List<String> proxies = new List<String>();


private static String getProxy()
{
    lock (proxies)
    {
        return proxies[new Random().Next(0, proxies.Count)];
    }
}

它不是空的,里面有一个代理,错误不在我的加载功能中,它就在这里。

我添加了一个断点并对其进行了调试,代理的值为Count = 3,proxies.count的值为3.

1 个答案:

答案 0 :(得分:0)

@Gendolkari的回答:

  

如果代理根本不包含任何元素,那么它会尝试   访问空列表的第一个元素并抛出此异常。

return proxies[new Random().Next(0, proxies.Count)];

==&GT;

return proxies[new Random().Next(0, 0)];

==&GT;

return proxies[0];

这会导致List(T).Item文档中所述的ArgumentOutOfRangeException,因为代理是空的。

相关问题