微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – OOP组成

我有一个关于OOP成分的问题.

假设一位母亲有0或更多的孩子,而且一个孩子只有一个生物学母亲.

为了说明这一点,我做了以下事情:

public class Mother : ObservableObject
{
    // [...]

    ObservableCollection<Child> Children {get; set;}
}

public class Child : ObservableObject
{
    public Child(Mother mother)
    {
        this.Mother = mother;

        // Adding the child to the mother's children collection
        mother.Children.Add(this);
    }

    public Mother Mother {get; set;}
}

但我想知道是否可以自动将孩子添加到母亲的收藏中,或者我是否应该使用以下内容

Mother mother = new Mother();

Child child = new Child(mother);
mother.Children.Add(child);

谢谢 :)

解决方法

我更喜欢,

public class Mother : ObservableObject
{
    // ...

    public Child GiveBirth()
    {
        var newBorn = new Child(this);
        this.Children.Add(newBorn);
        return newBorn;
    }

    // ...
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐