我有一个关于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; } // ... }