4

它在 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<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(这是用户的新声明)

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>();
}

我真的很困惑我做错了什么。任何帮助将不胜感激。

4

1 回答 1

15

如果该偏移量不存在,则无法索引到列表中。因此,例如,索引一个空列表总是会引发异常。使用诸如Add将项目附加到列表末尾或Insert将项目放置在列表中间某处等方法。

例如:

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列表中读取时发生的。

于 2010-11-21T05:54:53.720 回答