OOP组成

Sea*_*arp 3 c# oop composition

我有一个关于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;}
}
Run Code Online (Sandbox Code Playgroud)

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

Mother mother = new Mother();

Child child = new Child(mother);
mother.Children.Add(child);
Run Code Online (Sandbox Code Playgroud)

谢谢 :)

Jod*_*ell 5

我更喜欢,

public class Mother : ObservableObject
{
    // ...

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

    // ...
}
Run Code Online (Sandbox Code Playgroud)