检测亲属
本文关键字:检测 | 更新日期: 2023-09-27 18:35:47
我正在做一个像这样的虚拟村庄项目。 有 50 个男人和 50 个女人,他们变老并随机与某人结婚,他们有孩子,当他们达到 80 岁时,他们开始死亡。我有一个名为 Human 的抽象 C# 类:
abstract class Human
{
enum GenderType { Male, Female };
int Age;
bool Alive;
string Name;
GenderType Gender;
Human Father;
Human Mother;
Human Partner;
Human[] Children;
public abstract bool Check(ref List<Human> People, int Index);
}
还有两个来自人类阶层的孩子,叫做男人和女人。我的问题是我如何覆盖男人/女人类中的检查方法,以便能够检测非法结婚的女性/男性亲属。例如母亲、姐妹、阿姨、嫂子、岳母等。
就个人而言,我会将帮助程序属性添加到不同关系的基类中。使高级代码非常易于遵循。您只需根据需要为不同的关系添加新的帮助程序/属性即可。
像这样:
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
而不是列表来执行此操作,但是您还需要考虑目标受众:)