就我个人而言,我会为不同的关系向基类添加辅助属性。使高级代码非常容易理解。您只需根据需要为不同的关系添加新的助手/属性。
像这样的东西:
public class Human
{
...
public List<Human> Parents
{
get {return new List<Human>(){Mother, Father};}
}
public List<Human> Siblings
{
get
{
List<Human> siblings = new List<Human>();
foreach (var parent in Parents)
{
siblings.AddRange(parent.Children);
}
return siblings;
}
}
}
public class Man : Human
{
public override bool Check(ref List<Human> People, int Index)
{
// Do basic checks first
if (!base.Check(People, Index))
{
return false;
}
var person = People[Index];
// Can't marry your mother/father
if (this.Parents.Contains(person)
{
return false;
}
// Can't marry your sister/brother
if (this.Siblings.Contains(person))
{
return false;
}
// ... etc for other relationships
return true; /// Not rejected... yes you can marry them... (if they want to!)
}
}
我还将适用于男性和女性的基本检查放在Human
课堂上,并首先从男性和女性检查中调用基本检查(如上面的代码所示)。
public class Human
{
public virtual bool Check(ref List<Human> People, int Index)
{
var person = People[Index];
// Can't marry yourself!
if (this == person)
{
return false;
}
if (this.Gender == person.Gender)
{
return false; // Unless the village is New York or Brighton :)
}
if (!person.Alive)
{
return false; // Unless vampires/zombies are allowed
}
if (Partner != null)
{
return false; // Unless village supports bigamy/poligamy in which case use a collection for Partner and rename to Partners.
}
}
}
我想你会发现大多数检查同样适用于男性和女性,因为同性检查很早就发生了,所以大多数检查可能会进入基类Check
。
注意:是的,您可以使用而不是列表来做很多这样的事情yield return
,但是您还需要考虑目标受众:)