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;
    }

    // ...
}

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...