Skip to main content
 首页 » 编程设计

c#之在另一个类中使用一个类中的对象

2024年02月23日21lovecherry

我有两个类(class) Teacher 和 Student。我想让老师在学生中使用类功能。我遇到的问题是我需要在 Teacher 中使用的学生对象的数量是随机的。我以为我在构造函数中解决了这个问题,但我不得不在我使用学生的每个教师函数中声明新的学生对象。这样就创建了一个新的学生对象,这对我没有好处。这是我的代码

class Teacher 
{ 
    private bool absence; 
    private bool level; 
    private static int uniqueID = 0; 
    private ArrayList arrayList = new ArrayList(); 
    private ArrayList arrayList1 = new ArrayList(); 
    private int id = 0; 
    private int numPages; 
    private char present; 
    Random random = new Random(); 
    int randomLevel = random.Next(20, 30);//this line does not work, if I could then I would just use randomLevel in the in the line below for creating my student objects 
    Student student = new Student(); 
    int maybe; 
 
    public Teacher() 
    { 
        int randomLevel = random.Next(1, 3); 
        id = uniqueID; 
        absence = false; 
        level = (randomLevel % 2 == 0); 
        uniqueID++; 
        randomLevel = random.Next(20, 30); 
        Student[] student = new Student[randomLevel]; 
        maybe = randomLevel; 
        for (int i = 0; i < randomLevel; i++) 
        { 
            student[i] = new Student(); 
        } 
    } 

这是一个使用学生的教师函数

  public void addPages()//Come back need to add specific child 
  { 
        int choice = 0; 
        Console.WriteLine("Enter the student ID"); 
        choice = int.Parse(Console.ReadLine()); 
        Student[] student= new Student[maybe];//If i get rid of this line then how will I choose which student object to use.  However this created a new student object and I do not want to do that 
 
        student[choice] = new Student(); 
        int number = 0; 
        if (student[choice].absent()) 
        { 
            number = student[choice].excused(); 
        } 
        else 
        { 
 
            Console.WriteLine("How many pages did the student read today? "); 
            number = int.Parse(Console.ReadLine()); 
        } 
        student[choice].add(number);            
   } 

有没有办法让随机在构造函数上面的声明区工作?

请您参考如下方法:

我认为您的问题归结为变量范围,但您提供了相当多的无关代码。我将简化为我认为您真正关心的内容。

class Teacher 
{ 
    // class-level list of students 
    private List<Student> _students = new List<Student>(); 
 
    public Teacher() 
    { 
        var random = new Random(); 
        var studentCount = random.Next(20,30); 
 
        for(int i = 0; i < studentCount; i++) 
        { 
            _students.Add(new Student()); 
        } 
    } 
 
    // use _students from here on out 
    public void AddPages(...) { ... } 
}