我正在使用一个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();
}
}
然后我这样做:
if (list[list.Count -1].rank == list.Count)
答案 0 :(得分:0)
好吧,如果list.count = 0(即一个空列表)并从中减去1,它将抛出该异常。
答案 1 :(得分:0)
正如Damon先前所说,如果你有一个从0开始的arraylist并且你从0减去1,那么你得到的-1就数组/ arraylists来说是不存在的。
以这种方式思考,数组超出范围的唯一方法是当程序在不存在时请求数组键。例如:
//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