初始化List上的ArgumentOutOfRangeException

它在For循环的中间抛出一个ArgumentOutOfRangeException,请注意我删除了for循环的其余部分

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 Direct_Assoc; public List 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 Units = new List(); } 

和CurrentUser(这是用户的新声明)

 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 Course_ID = new List(); public List Course = new List(); } 

我真的只是因为我做错了而大肆混淆。 任何帮助将非常感谢。

如果该偏移量不存在,则无法索引到列表中。 因此,例如,索引空列表将始终抛出exception。 使用像Add这样的方法将项目附加到列表的末尾,或者使用Insert将项目放在列表中间的某个位置,等等。

例如:

 var list = new List(); list[0] = "foo"; // Runtime error -- the index 0 doesn't exist. 

另一方面:

 var list = new List(); 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列表中读取时,会发生这种情况。