如何在c#中实施师生关系?
我想实现一个系统,它代表了课堂与学生的关系。我想施加一个限制,每个教室可以有任意数量的学生,但一个学生只能在一个教室 我创建了两个类-教室和学生。我已经在课堂上创建了一个列表。我如何确保没有人可以在两个课堂上插入同一个学生。在C#中,给定一个如何在c#中实施师生关系?,c#,class,model-associations,relationships,C#,Class,Model Associations,Relationships,我想实现一个系统,它代表了课堂与学生的关系。我想施加一个限制,每个教室可以有任意数量的学生,但一个学生只能在一个教室 我创建了两个类-教室和学生。我已经在课堂上创建了一个列表。我如何确保没有人可以在两个课堂上插入同一个学生。在C#中,给定一个IEnumerable教室,其中教室有一个属性学生,即IEnumerable 我希望这是你的经验: 教室 public class ClassRoom { private List<Student> students = new List
IEnumerable教室
,其中教室
有一个属性学生
,即IEnumerable
我希望这是你的经验: 教室
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;
}
}
通过检查所有教室以确保学生尚未被插入。如果有两个子类classroom1和classroom2,如何迭代所有对象?如何获取所有教室对象?请参阅我的答案,其中classroom1和classroom2将添加到教室对象列表中。我的回答是否有帮助?如果是的话,你能标为接受吗?
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
}
}
}