检测亲戚?

时间:2012-05-31 11:00:07

标签: c#

我正在开发一个像这样的虚拟村庄项目。有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);
}

和两个来自人类的孩子叫男人和女人。我的问题是我如何能够覆盖男/女班的检查方法,以便能够检测出与之结婚的非法男性/男性亲属。例如母亲,姐妹,阿姨,嫂子,法律上的母亲等。

1 个答案:

答案 0 :(得分:2)

我个人会为不同的关系添加辅助属性到基类。使高级代码非常容易理解。您只需根据需要为不同的关系添加新的帮助器/属性。

像这样:

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代替列表来执行大量此操作,但您还需要考虑目标受众:)