【发布时间】:2015-02-16 13:48:06
【问题描述】:
我想创建一个递归函数,它将添加到下面列出的nestedContainer 对象中,无论基于多维数组的长度如何。根将为零,只要您从根开始工作,您就可以随心所欲地添加。所以0 将包含0.0, 0.1, 0.2 和0.0 将包含0.0.0, 0.0.1, 0.0.2 等等。必须先创建父级,然后才能存在子级。
public class Container()
{
public List<Container> container {get; set;}
public string containerName {get; set;}
public string index {get; set;}
}
public class ContainerBuilder()
{
//This is the main container that will contain all of the children
Container nestedContainer = new Container();
//This method will take in the parent index value and then will add the new container into the parent container list based on the value specified
public void AddContainer(string parentIndex, string containerName, string index)
{
Container container = new Container()
{
index = index,
name = name,
container = new List<Container>()
}
SetContainer(parentIndex, index, container);
}
private void SetContainer(string, parentIndex, string index, Container container)
{
//Recurive function that will add the new container in the parent container working its way back from the parent
//Get the root container, a starting point to add the children
var rootContainer = nestedContainer .contains[int.Parse(parentIndex.Split('.')[0])];
}
}
实施
ContainerBuilder builder = new ContainerBuilder();
builder.AddContainer("0", "Parent 0", "0");
builder.AddContainer("0", "Child of parent", "0.x");
builder.AddContainer("0.x", "child of child", "0.x.x");
builder.AddContainer("0.x.x", "child of a child of a child", "0.x.x.x");
只要路径匹配,您就会看到索引应该是无关紧要的,因此无论您采用哪种方式,都可以添加任意数量的子节点。
【问题讨论】:
-
在您的示例中,如何找到父母? “此方法将获取父索引值,然后将新容器添加到父容器列表中” - 什么父容器列表?
-
请修复您的
""和,,现在很难阅读。 -
我不确定,这也是我为此苦苦挣扎的原因。我想你可以从根容器开始,然后向下工作
-
@MikeBarnes 这就是我的观点,示例中没有“起点”,这里的
nestedContainer是什么?那是根容器吗?例子不是很清楚... -
nestedContainer是包含所有嵌套子级的主容器。我真的很难把我的想法写在这里,根是nestedContainer中的第一级容器,所以nestedContainer.container