我想为我创建的对象添加一个堆栈,但我不知道如何实现它。假设我创建了5个对象(学生),并想为每个学生对象添加一个堆栈(成绩),我该怎么做?
在我的主要方法中,我创建了一个学生对象
Student student1 = new Student
{
FirstName = "John",
LastName = "Wayne",
BirthDate = "26/05/1907"
};
我有另一个对象课程并将学生添加到其中
course.AddStudent(student1);
我在代码中进一步创建了一个学生对象
public class Student : Person
{
public static int count = 0;
// Stack of student grades
Stack grades= new Stack();
// Stack<int> grades = new Stack<int>();
public Student()
{
// Thread safe since this is a static property
Interlocked.Increment(ref count);
}
public void TakeTest()
{
Console.WriteLine("Student takes test for course...");
}
}
如何为每个学生对象添加堆栈?
答案 0 :(得分:1)
修改您的Student
class
并添加Stack<int> Grades
然后在constructor
中创建Grades Stack
public class Student{
//rest of properties
public Stack<int> Grades { get; private set; }
public Student()
{
//rest of the code
Grades = new Stack<int>();
}
}
更新1:
要设置成绩,您可以向Student class
添加新方法以添加成绩
public void AddGrade(int grade)
{
this.Grades.Push(grade);
}
有关Stack<int>
here
比创建Student对象后只需调用
student1.AddGrade(5) instead of student1.Grades.AddGrade(5)
更新2:
要打印Grades
值,您应手动迭代Grades
方法中的main
堆栈
foreach(int grade in student1.Grades)
{
Console.WriteLine(grade);
}