【问题标题】:How to iterate through ArrayList and cast the returned object into another object如何遍历ArrayList并将返回的对象转换为另一个对象
【发布时间】:2015-04-27 13:36:05
【问题描述】:

(这是一个学术问题)

我创建了一个 Arraylist 来保存学生对象。现在我需要将它们转换回原始类型并在控制台上打印出来。我需要在一个对象中创建一个方法,该方法将遍历所有对象(在它们被转换回之后)并将它们打印出来 -

如何将返回的对象从 ArrayList 转换为 (Student) 对象。

在课程对象中,我创建了一个名为 studentarraylist 的 ArrayList

public class Course
        {
            ArrayList studentarraylist = new ArrayList();

在那个课程对象中,我创建了一个添加学生的方法

public void AddStudent(Student student)
            {
                studentarraylist.Add(student);          
             }

在 main 中 - 我使用该方法向 ArrayList 添加了一个学生对象

course.AddStudent(student1);

现在我需要在 Course 中创建一个方法来将对象转换回原始类型,使用 foreach 循环遍历 ArrayList 中的学生并将他们的名字和姓氏输出到控制台窗口。我有点搞混了,因为我无法访问方法中的某些项目 - 当我在 main 中创建它们时。

public void liststudents(ArrayList studentarraylist)
            {
                Course studentoneout = (Course)studentarraylist[0];


                 for (int i = 0; i < studentarraylist.Count; ++i)
                {
                    //Console.WriteLine(studentarraylist[i]);
                    Console.WriteLine("student first name", studentarraylist.ToString());
                    Console.WriteLine("");
                }
            }

编辑***

public class Course
        {
            ArrayList studentarraylist = new ArrayList();

            private string courseName;
            //Create a course name          
            public string CourseName
            {
                get { return courseName; }
                set { courseName = value; }
            }       

            //add student method
            public void AddStudent(Student student)
            {
                studentarraylist.Add(student);          
             }



             public void liststudents(ArrayList studentarraylist)
            {

                for (int i = 0; i < studentarraylist.Count; i++)
                {
                    Student currentStudent = (Student)studentarraylist[i];
                    Console.WriteLine("Student First Name: {0}", currentStudent.FirstName); // Assuming FirstName is a property of your Student class
                    Console.WriteLine("Student Last Name: {0}", currentStudent.LastName);
                    // Output what ever else you want to the console.
                }

                 // Course studentoneout = (Course)studentarraylist[0];





//                 for (int i = 0; i < studentarraylist.Count; ++i)
 //               {
  //                  Student s = (Student)studentarraylist[i];

   //             }
            }

【问题讨论】:

  • 您认为 studentarraylist 是学生列表,但我看到您将对象投射到课程???
  • 我的代码可能不是很干净——我尝试了一些东西。我试图在 Course 中添加项目,但它不起作用,而是将它们添加到 main 中。我试图将它们转换为原始类型,但没有找到。

标签: c#


【解决方案1】:

首先,您不应该为此使用ArrayList。通用 List&lt;Student&gt; 是您在此处列出的所需内容。

但是,如果您必须坚持使用ArrayList,它不包含任何Course 对象,仅包含Student 对象。所以第一次演员应该失败:

(Course)studentarraylist[0]

现在,如果您想在列表项上调用学生特定的方法,您需要确保将它们转换为正确的类型,在这种情况下为Student

for (int i = 0; i < studentarraylist.Count; ++i)
{
    Student s = (Student)studentarraylist[i];
    ...
}

另外,如果你想遍历你已经添加的学生,你不需要向liststudents 传递任何东西——你已经在类实例中有一个字段可以使用。所以应该是

public void liststudents()
{
    for (int i = 0; i < studentarraylist.Count; ++i)
    {
        Student s = (Student)studentarraylist[i];
        ...
    }
}

以及Course类的用法:

Course c = new Course();
c.AddStudent(student1);
c.AddStudent(student2);
c.liststudents();

最后一件事 - 除非有确凿的理由,否则不要使用像 liststudents 这样的无大写名称。根据 C# 标准,它应该是 ListStudents

【讨论】:

    【解决方案2】:

    您的问题有点令人困惑,但您的liststudents() 似乎是问题所在。当您从 studentarraylist 中提取项目时,您应该将其转换为 Student 对象,而不是 Course 对象。

    编辑

    liststudents() 中取出参数,因为您的Course 类中已经定义了ArrayList。您不必将ArrayList 传递给您的班级已经知道的班级。

    public void liststudents()
    {
        for (int i = 0; i < studentarraylist.Count; i++) 
        {
            Student currentStudent = (Student)studentarraylist[i];
            Console.WriteLine("Student First Name: {0}", currentStudent.FirstName); // Assuming FirstName is a property of your Student class
            Console.WriteLine("Student Last Name: {0}", currentStudent.LastName);
            // Output what ever else you want to the console.
        }
    }
    

    然后你会像这样使用 main 中的 liststudents()...

    Course myCourse = new Course();
    myCourse.AddStudent(someNewStudentYouMade);
    myCourse.AddStudent(someNewStudentYouMade);
    myCourse.AddStudent(someNewStudentYouMade);
    myCourse.AddStudent(someNewStudentYouMade);
    myCourse.AddStudent(someNewStudentYouMade);
    myCourse.liststudents();
    

    【讨论】:

    • 那种看起来不错,但我仍在思考它。看起来它正在转换为原始类型,然后打印出名字和姓氏! - 我将传递给 course.liststudents() 什么; ?
    • @Aindriu 我以为 liststudents() 在你的课程中?您可以发布您的课程课程和学生课程吗?
    • 是的,它在 Course 中,但我从 main 调用方法 course.liststudent()。
    • 哇!那行得通。我只是希望它在打印出来之前进行投射
    【解决方案3】:

    在你的 for 循环中,你实际上并没有打印出学生,而是整个列表。

    解决这个问题的一种方法是在我喜欢的位置打印出学生的名字:

    for (int i = 0; i < studentarraylist.Count; ++i)
        {
             Console.WriteLine("student first name", studentarraylist[i].Name.ToString());
             Console.WriteLine("");
        }
    

    【讨论】:

    • 由于 OP 使用的是 ArrayList,因此使用 foreach 遍历 ArrayList 可能不是一个好主意,因为不能保证 ArrayList 中的所有对象都是 Student 类型。跨度>
    • 他们都是学生类型,我需要使用 foreach 循环
    • @Shar1er80 你说得对,我会从我的答案中删除那部分。但是,正如最佳答案所说,OP 应该使用List&lt;Student&gt;
    • 那么正如@Andrei 所建议的,您应该使用 System.Collections.Generic 命名空间中的 List。您将在 Course 类中有一个 List,然后您就不必为任何转换而烦恼。
    【解决方案4】:

    使用 foreach - 隐式转换

    如果它在主目录中

    foreach (Student student in MyCourseObject.Students)
    {
        Console.WriteLine("{0} {1}", student.FirstName, student.LastName);
    }
    

    如果在课程类中

    public void ListStudents()
        {
            foreach (Student s in this.Students)
            {
               Console.WriteLine("{0} {1}", s.FirstName, s.LastName);
            }
        }
    

    使用 for 循环 - 显式转换

    主要

    for (int i = 0; i < MyCourseObject.Students.Count; i++)
    {
        Student student = (Student)MyCourseObject.Students[i];
        Console.WriteLine("{0} {1}", student.FirstName, student.LastName);
    }
    

    如果在课程中

    public void ListStudents()
        {
             for (int i = 0; i < this.Students.Count; i++)
             {
                 Student student = (Student)this.Students[i];
                 Console.WriteLine("{0} {1}", student.FirstName, student.LastName);
             }
         }
    

    为此假设:

    • Course Class 中定义了一个 Student ArrayList。

    • MyCourseObject 是 Course 类的一个实例。

    • Students 是包含 Student 类型的对象(实例)的 Arraylist。

    【讨论】:

      猜你喜欢
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      相关资源
      最近更新 更多