(这是一个学术问题)
我创建了一个Arraylist来容纳学生对象.现在我需要将它们转换回原始类型并在控制台上打印出来.我需要在一个对象中创建一个方法来循环遍历所有对象(在它们被抛回之后)并将它们打印出来 -
如何将返回的对象从ArrayList转换为(Student)对象.
在课程对象中,我创建了一个名为studentarraylist的ArrayList
public class Course
{
ArrayList studentarraylist = new ArrayList();
Run Code Online (Sandbox Code Playgroud)
在该课程对象中,我创建了一个添加学生的方法
public void AddStudent(Student student)
{
studentarraylist.Add(student);
}
Run Code Online (Sandbox Code Playgroud)
在main中 - 我使用该方法向ArrayList添加了一个student对象
course.AddStudent(student1);
Run Code Online (Sandbox Code Playgroud)
现在我需要在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("");
}
}
Run Code Online (Sandbox Code Playgroud)
编辑***
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];
// }
}
Run Code Online (Sandbox Code Playgroud)
首先,你不应该使用ArrayList它.Generic List<Student>是您在此处列表所需的内容.
但是,如果你必须坚持ArrayList,它不包含任何Course对象,只包含任何对象Student.所以第一次演员应该失败:
(Course)studentarraylist[0]
现在,如果要在列表的项目上调用学生特定的方法,则需要确保将它们转换为正确的类型,Student在这种情况下:
for (int i = 0; i < studentarraylist.Count; ++i)
{
Student s = (Student)studentarraylist[i];
...
}
Run Code Online (Sandbox Code Playgroud)
此外,如果您想迭代已经添加的学生,则不需要传递任何内容liststudents- 您已经在类实例中使用了一个字段.所以它应该是
public void liststudents()
{
for (int i = 0; i < studentarraylist.Count; ++i)
{
Student s = (Student)studentarraylist[i];
...
}
}
Run Code Online (Sandbox Code Playgroud)
以及Course该类的用法:
Course c = new Course();
c.AddStudent(student1);
c.AddStudent(student2);
c.liststudents();
Run Code Online (Sandbox Code Playgroud)
最后一件事 - 除非有一个很难的理由,否则不要使用像帽子这样的无名字liststudents.它应该符合ListStudentsC#标准.