c#是一个参考

本文关键字:一个 参考 | 更新日期: 2023-09-27 18:06:38

在类的顶部,在字段members中,Teacher的名称是什么;

我知道这允许我们访问Teacher类;它的属性和方法。我想知道它是被称为一个引用还是一个类的实例,这样我就可以多读一点来澄清我对它的理解。

谢谢。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace P3_O_O_P
{
    public class Classroom
    {
        private int roomNo;
        private string className;
        Teacher teacher;
        public List<Student> stuList = new List<Student>();
        public Classroom(int newRoomNo, string newRoomName)
        {
            roomNo = newRoomNo;
            className = newRoomName;
        }
        public Classroom()
        {
        }
        public void addStudent(string studentName, int studentID)
        {
            stuList.Add(new Student(studentName, studentID));
        }
        public void addTeacher(string teacherName, int teacherID)
        {
            teacher = new Teacher(teacherName, teacherID);
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("'nTeacher name: " + teacherName + "'nTeacher ID: " + teacherID + "'nSystem updated!'n");
        }
        public void viewClass()
        {
            for (int i = 0; i < stuList.Count; i++)
            {
                Console.WriteLine(stuList[i].toString());
            }
            if (teacher != null)
            {
                Console.WriteLine(teacher.toString());
            }
        }
        public void removeTeacher()
        {
            teacher = null;
        }
        public string ClassName
        {
            get
            {
                return className;
            }
            set
            {
                className = value;
            }
        }
        public int ClassNumber
        {
            get
            {
                return roomNo;
            }
            set
            {
                roomNo = value;
            }
        }
        public void removeStudent(int id)
        {
            for (int i = 0; i < stuList.Count(); i++)
            {
                int ID = stuList[i].ID;
                if (id == ID)
                {
                    Console.WriteLine("'nStudent name: {0}'nStudent number: {1}'n'nStudent removed from classroom'n'nSystem updated!'n'n", stuList[i].Name, stuList[i].ID);
                    stuList.RemoveAt(i);
                }
            }
        }
    }
}

c#是一个参考

Teacher为类名。teacher是对teacher类实例的引用。

另一种思考方式:teacherTeacher类型的变量

创建一个Teacher类型的teacher。通过创建一个对象,我们可以访问它的公共成员。

teacherTeacher类型的成员变量,它是引用类型(而不是类型)。一旦通过addTeacher()方法实例化了teacher,它将引用Teacher类的特定实例。