初始化List上的ArgumentOutOfRangeException

Jar*_*ner 4 .net c# exception list outofrangeexception

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

for (int i = 0; i < CurrentUser.Course_ID.Count - 1; i++)
{    
    CurrentUser.Course[i].Course_ID = CurrentUser.Course_ID[i];
}
Run Code Online (Sandbox Code Playgroud)

课程代码是

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>();
}
Run Code Online (Sandbox Code Playgroud)

和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<string> Course_ID = new List<string>();
    public List<Course> Course = new List<Course>();
}
Run Code Online (Sandbox Code Playgroud)

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

cdh*_*wie 13

如果该偏移量不存在,则无法索引到列表中.因此,例如,索引空列表将始终抛出异常.使用类似的方法Add将项目附加到列表的末尾,或者Insert将项目放在列表的中间位置等.

例如:

var list = new List<string>();
list[0] = "foo"; // Runtime error -- the index 0 doesn't exist.
Run Code Online (Sandbox Code Playgroud)

另一方面:

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.
Run Code Online (Sandbox Code Playgroud)

请注意,在您的代码中,当您写入Courses列表时,而不是从Course_ID列表中读取时,会发生这种情况.