初始化列表上的 ArgumentOutOfRangeException [英] ArgumentOutOfRangeException on initialized List

查看:18
本文介绍了初始化列表上的 ArgumentOutOfRangeException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它在 For 循环的中间抛出了 ArgumentOutOfRangeException,请注意我剪掉了 for 循环的其余部分

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

课程代码是

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(这是 User 的新声明)

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.

推荐答案

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

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.

例如:

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

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.

这篇关于初始化列表上的 ArgumentOutOfRangeException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆