如何将堆栈添加到对象 C#

  • 本文关键字:对象 添加 堆栈 c#
  • 更新时间 :
  • 英文 :


我想为我创建的对象添加一个堆栈,但我不知道如何实现它。 假设我创建了 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...");
        }
    }

如何为每个学生对象添加堆栈?

修改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>

这里

比创建学生对象后只需调用

student1.AddGrade(5) instead of student1.Grades.AddGrade(5)

更新 2:为了打印Grades值,您应该在main方法中手动迭代Grades堆栈

foreach(int grade in student1.Grades)
{
    Console.WriteLine(grade);
}

最新更新