Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

c# - ArgumentOutOfRangeException on initialized List

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];
}

The Code for Course is

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

For example:

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

On the other hand:

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...