问题描述
因此,在一个典型的模型中,您有一个可以有多个孩子的父母和一个只能有一个父母的孩子,您如何管理孩子的添加.我一直在使用这种方法;
So in a typical model where you have a parent that can have many children and a child that can have only one parent, how do you manage the adding of children. I have been using this approach;
public class Parent
{
public Parent()
{
Children = new List<Child>();
}
public IList<Child> Children
{
get;
private set;
}
}
public class Child
{
public Parent Parent
{
get;
set;
}
}
var child = new Child();
var parent = new Parent();
parent.Children.Add(child);
child.Parent = parent;
问题在于,我想添加一个新孩子的任何地方,我都必须记住要添加对孩子和父母的引用,这有点麻烦.我可以将AddChild方法添加到父类中,并让它负责添加子项-现在的问题是,通过Children属性和方法,有两种添加子项的方法.那么这是一个更好的解决方案吗?
Problem is that everywhere i want to add a new child i've got to remember to add a reference to both the child and parent and its a bit of a pain. I could just add an AddChild method to the parent class and make that responsible for adding children - the problem now is that there is 2 ways to add a child, through the Children property and the method. So is this a better solution?
public class Parent
{
public Parent()
{
children = new List<Child>();
}
private IList<Child> children
{
get;
private set;
}
public IEnumerable<Child> Children
{
get
{
return children;
}
}
public void AddChild(Child child)
{
children.Add(child);
child.Parent = this;
}
}
是否有关于最佳实践的指南,您该怎么办?
Are there any guidences for best practices on this, and what do you do?
推荐答案
除了不将属性用于私有列表外,我这样做像
I do it like that except that I don't use property for private list
private IList<Child> _children
public IEnumerable<Child> Children
{
get
{
return children;
}
}
这篇关于处理NHibernate亲子集合的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!