C# I';我有一个超出范围的论点

C# I';我有一个超出范围的论点,c#,arraylist,C#,Arraylist,我使用的是arraylist,它有一个列表[list.Count-1],它给了我参数超出范围的异常,为什么?如果列表的计数是它包含的元素数,则列表[list.count]不应超出范围,这就是我向列表添加项目的方式: string query = "SELECT Title, Type, Contents, Rank,Audio FROM dbo.Article,dbo.ArticleJournal WHERE dbo.Article.ArticleId = dbo.ArticleJournal.

我使用的是arraylist,它有一个列表[list.Count-1],它给了我参数超出范围的异常,为什么?如果列表的计数是它包含的元素数,则列表[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();
    }
}

好的,如果list.count=0(即一个空列表),你从中减去1,它将抛出该异常。

正如Damon之前所说,如果你有一个从0开始的arraylist,并且你从0中减去1,那么你得到的是-1,它在数组/arraylist中并不存在

这样想一想,数组将超出边界的唯一方式是当程序在它不存在的情况下请求数组键时。例如:

//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

如果是空的呢?好的。我们可以看看您是如何在arrayList中添加元素的吗?顺便提一下,为什么您仍然使用arrayList,而不是泛型集合?发生错误时,
list.Count
的值是多少?为什么要使用try finally块?您的使用范围将关闭连接
//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