[英]System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'
This error is appearing when it reaches the classes[0].AddLesson(one);当它到达 classes[0].AddLesson(one); 时出现此错误; line and I have no idea why this is happening?行,我不知道为什么会这样? any ideas would be great... I have two classes btw Lesson and Timetable任何想法都会很棒......我有两节课顺便说一下课程和时间表
List<Timetable> classes = new List<Timetable>();
private void Form1_Load(object sender, EventArgs e)
{
Lesson one = new Lesson("maths", 1, 2);
Lesson two = new Lesson("science", 3, 4);
classes[0].AddLesson(one);
classes[1].AddLesson(two);
DisplayList(classes);
}
void DisplayList(List<Timetable> timetable)
{
lstTimetable.Items.Clear();
foreach(Timetable t in timetable)
{
lstTimetable.Items.Add(t);
}
}
You have created a new list here:您在此处创建了一个新列表:
List<Timetable> classes = new List<Timetable>();
But you haven't added anything to that list so it had no length (zero indexes).但是您尚未向该列表添加任何内容,因此它没有长度(零索引)。 When you try to assign a value to the first index of the list here:当您尝试在此处为列表的第一个索引赋值时:
classes[0].AddLesson(one);
You're getting the exception because index 0 doesn't exist.您收到异常,因为索引 0 不存在。
If you want to add to a list you do:如果要添加到列表中,请执行以下操作:
classes.Add(one);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.