ingumentOutoFrangeException في القائمة المهيئة
-
26-09-2019 - |
سؤال
إنه يلقي bigumentOutoFrangeException في منتصف الحلقة ، يرجى ملاحظة أنني قطعت بقية الحلقة 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>();
}
أنا في الواقع في حيرة من أمري مع ما أفعله خطأ. أي مساعدة سيكون موضع تقدير كبير.
المحلول
لا يمكنك الفهرس في قائمة إذا لم يكن موجودًا. لذلك ، على سبيل المثال ، فإن فهرسة قائمة فارغة ستلقي دائمًا استثناء. استخدم طريقة مثل 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
قائمة.
لا تنتمي إلى StackOverflow