gpt4 book ai didi

c# - 如何遍历 ArrayList 并将返回的对象转换为另一个对象

转载 作者:太空宇宙 更新时间:2023-11-03 18:05:56 25 4
gpt4 key购买 nike

(这是学术问题)

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

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

在类(class)对象中,我创建了一个名为 studentarraylist 的 ArrayList

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

在那个类(class)对象中我创建了一个添加学生的方法

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

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

course.AddStudent(student1);

现在我需要在 Course 中创建一个方法来将对象转换回原始类型,使用 foreach 循环遍历 ArrayList 中的 Students 并将他们的名字和姓氏输出到控制台窗口。我有点困惑,因为我无法访问方法中的某些项目 - 当我在 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];

// }
}

最佳答案

你不应该使用 ArrayList为此,首先。通用 List<Student>是您的列表所需要的。

但是如果你必须坚持 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 这样的无大写名称。 .应该是ListStudents根据 C# 标准。

关于c# - 如何遍历 ArrayList 并将返回的对象转换为另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29897343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com