ArgumentOutOfRangeException na lista inicializada
-
26-09-2019 - |
Pergunta
Ele está jogando uma argumentação de reprodução no meio do loop for, observe que eu cortei o resto do loop for
for (int i = 0; i < CurrentUser.Course_ID.Count - 1; i++)
{
CurrentUser.Course[i].Course_ID = CurrentUser.Course_ID[i];
}
O código do curso é
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>();
}
e CurrentUser (que é uma nova declaração de usuário)
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>();
}
Estou realmente flagrantemente confuso quanto ao que estou fazendo de errado. qualquer ajuda seria muito bem vinda.
Solução
Você não pode indexar em uma lista se esse deslocamento não existir. Por exemplo, a indexação de uma lista vazia sempre lançará uma exceção. Use um método como Add
Para anexar o item ao final da lista, ou Insert
Para colocar o item no meio da lista em algum lugar, etc.
Por exemplo:
var list = new List<string>();
list[0] = "foo"; // Runtime error -- the index 0 doesn't exist.
Por outro lado:
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.
Observe que em seu código, isso está acontecendo quando você Escreva para o Courses
Lista, e não quando você lê do Course_ID
Lista.