【问题标题】:ArgumentOutOfRangeException on initialized List初始化列表上的 ArgumentOutOfRangeException
【发布时间】:2011-05-13 07:20:16
【问题描述】:

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

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

【问题讨论】:

  • List 很可能是空的。您在代码中的哪个位置初始化并向其添加值?

标签: c# .net list exception outofrangeexception


【解决方案1】:

如果该偏移量不存在,则无法索引到列表中。因此,例如,索引一个空列表总是会引发异常。使用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 列表中读取时发生。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    相关资源
    最近更新 更多