问题描述
它在For循环的中间抛出ArgumentOutOfRangeException,请注意,我剪掉了其余的for循环
It's throwing an ArgumentOutOfRangeException in the middle of the For loop, please note that I cut out the rest of the for loop
for (int i = 0; i < CurrentUser.Course_ID.Count - 1; i++)
{
CurrentUser.Course[i].Course_ID = CurrentUser.Course_ID[i];
}
课程代码是
public class Course
{
public string Name;
public int Grade;
public string Course_ID;
public List<string> Direct_Assoc;
public List<string> InDirect_Assoc;
public string Teacher_ID;
public string STUTeacher_ID;
public string Type;
public string Curent_Unit;
public string Period;
public string Room_Number;
public List<Unit> Units = new List<Unit>();
}
和CurrentUser(这是User的新声明)
and CurrentUser (which is a new declaration of User)
public class User
{
public string Username;
public string Password;
public string FirstName;
public string LastName;
public string Email_Address;
public string User_Type;
public List<string> Course_ID = new List<string>();
public List<Course> Course = new List<Course>();
}
我真的只是对我做错了事感到很困惑.任何帮助将不胜感激.
I'm really just blatantly confused as to what I'm doing wrong. Any help would be very much appreciated.
推荐答案
如果该偏移量不存在,则无法索引到列表中.因此,例如,索引空列表将始终引发异常.使用Add
之类的方法将该项目附加到列表的末尾,或使用Insert
将其放置在列表中间的某处,等等.
You cannot index into a list if that offset doesn't exist. So, for example, indexing an empty list will always throw an exception. Use a method like Add
to append the item to the end of the list, or Insert
to place the item in the middle of the list somewhere, etc.
例如:
var list = new List<string>();
list[0] = "foo"; // Runtime error -- the index 0 doesn't exist.
另一方面:
var list = new List<string>();
list.Add("foo"); // Ok. The list is now { "foo" }.
list.Insert(0, "bar"); // Ok. The list is now { "bar", "foo" }.
list[1] = "baz"; // Ok. The list is now { "bar", "baz" }.
list[2] = "hello"; // Runtime error -- the index 2 doesn't exist.
请注意,在您的代码中,这是在写入Courses
列表时发生的,而不是在您从Course_ID
列表中读取时发生的.
Note that in your code, this is happening when you write to the Courses
list, and not when you read from the Course_ID
list.
这篇关于初始化列表上的ArgumentOutOfRangeException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!