【问题标题】:I'm having an argument out of bounds exception我的参数越界异常
【发布时间】:2014-01-04 23:49:35
【问题描述】:

我正在使用一个数组列表,并且有这个列表[list.Count -1],它给了我参数超出范围异常,为什么会这样?如果列表的计数是它包含的元素数,那么 list[list.count] 不应该超出范围,这就是我向列表中添加项目的方式:

string query = "SELECT Title, Type, Contents, Rank,Audio FROM dbo.Article,dbo.ArticleJournal WHERE dbo.Article.ArticleId = dbo.ArticleJournal.ArticleId AND dbo.ArticleJournal.JournalId LIKE @id ;";
List<Codes.ArticleJ> list = new List<Codes.ArticleJ>();
using (SqlConnection connection = new SqlConnection(
         connectionString))
{
    SqlCommand command = new SqlCommand(
        query, connection);
    try
    {
        connection.Open();
        command.Parameters.Add(new SqlParameter("@id", id));
        SqlDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            string Title = reader.GetString(0);
            string type = reader.GetString(1);
            String Contents = reader.GetString(2);
            int rnk = reader.GetInt32(3);
            String Audio = reader.GetString(4);

            Codes.ArticleJ article = new Codes.ArticleJ(Title, type,     Contents, rnk, Audio);
            list.Add(article);
        }
    }
    finally 
    { 
        connection.Close();
    }
}

那我就这样做了:

if (list[list.Count -1].rank == list.Count)

【问题讨论】:

  • 空了怎么办?
  • 好的。我们可以看看你是如何在 arrayList 中添加元素的吗?
  • 顺便说一句,您为什么仍然使用 ArrayList 而不是通用集合?
  • 出错时list.Count的值是多少?
  • 为什么会有 try-finally 块?您的使用范围将关闭连接

标签: c# arraylist


【解决方案1】:

好吧,如果 list.count = 0(即一个空列表)并且您从中减去 1,它将引发该异常。

【讨论】:

    【解决方案2】:

    正如 Damon 之前所说,如果您有一个从 0 开始的数组列表,并且您从 0 中减去 1,您将得到 -1,这在数组/数组列表方面不存在。

    这样想,数组越界的唯一方法是当你的程序请求一个不存在的数组键时。示例:

    //Say you had this array
    int [] myArray = new int [5];
    
    //Then you wanted to add a number to myArray[6]
    myArray[6] = 15;
    
    //You will get the exception because you did not define myArray to have 7 keys (0-6)
    
    //This also goes for negative integers
    myArray[-1] = 15; 
    
    //You will also get the exception because 0 is the lowest key an array can go
    //Negative numbers do not exist
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      相关资源
      最近更新 更多