【问题标题】:Why does this loop throw a System.ArgumentOutOfRangeException error, rather than ending?为什么这个循环会抛出 System.ArgumentOutOfRangeException 错误,而不是结束?
【发布时间】:2015-08-05 13:23:15
【问题描述】:

为什么我的循环无法结束?为什么它会抛出异常?

int i=0;

ArrayList item = new ArrayList();
ArrayList list = new ArrayList();

while (reader.Read())
{
    item.Add(reader["element"].ToString());//keep data from my SQL
}

string chk2 = textBox1.Text.ToString();

for ( i = 0; i <= item.Count;i++ )
{
    if ((item[i].ToString()).Contains(chk2) )//this line got error.
    {
        list.Add(item[i]);
        MessageBox.Show(item[i].ToString());
    }
    else
    {
        MessageBox.Show("Not Found");
    }
}

错误说明:在 mscorlib.dll 中发生了“System.ArgumentOutOfRangeException”类型的未处理异常

附加信息:索引超出范围。必须为非负数且小于集合的大小。

请问如何解决?

【问题讨论】:

标签: c# loops arraylist contains


【解决方案1】:

改变

for ( i = 0; i <= item.Count;i++ )

for ( i = 0; i < item.Count;i++ )

对于从 0 开始的索引,最后一个索引小于 item.Count 返回的值
在您的情况下,最后一个循环将尝试查找具有索引的项目,该项目不存在于数组中

&lt;= item.Count 更改为&lt; item.Count 将防止i 的值大于最后一个可能的索引

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多