如何实现c#中的类 - 学生关系?

时间:2015-05-03 19:22:44

标签: c# class model-associations relationships

我想实现一个代表ClassRoom- Student关系的系统。我想强制规定每个ClassRoom可以有任意数量的学生,但是一个学生只能在一个ClassRoom。

我创建了两个类 - ClassRoom和Student。我在Class ClassRoom中创建了一个列表。如何确保没有人可以在两个classRooms中同一个学生。

2 个答案:

答案 0 :(得分:0)

在C#中给出IEnumerable<ClassRoom> classRooms,其中ClassRoom的属性StudentsIEnumerable<Student>

public bool HasStudent(Student student)
{
    return classRooms.Any(c => c.Students.Any(s => s == student));
}

答案 1 :(得分:0)

我希望这是你的经验水平:

教室

public class ClassRoom
{
    private List<Student> students = new List<Student>();

    public bool Contains(Student student)
    {
        return this.students.Contains(student);
    }

    public void Add(Student student)
    {
        if (!Contains(student))
            this.students.Add(student);
        student.StudentClassRoom = this;
    }

    public void Remove(Student student)
    {
        // if this contains, remove it anyway...
        if(Contains(student))
            this.students.Remove(student);

        // but do not set ClassRoom of student if she/he does not sit in this.
        if (student.StudentClassRoom != this)
            return;

        student.StudentClassRoom = null;
    }
}

学生

public class Student
{
    private ClassRoom stdClsRoom;
    public ClassRoom StudentClassRoom
    {
        get { return this.stdClsRoom; }
        set
        {
            if (value == this.stdClsRoom) //from null to null; from same to same;
                return;                   //do nothing

            if (this.stdClsRoom != null)  //if it set from something
            {
                ClassRoom original = this.stdClsRoom;
                this.stdClsRoom = null;  // set field to null to avoid stackoverflow
                original.Remove(this);   // remove from original
            }

            this.stdClsRoom = value;    // set field

            if (value != null)          //if it set to something
                value.Add(this);        // add to new
        }
    }
}