我有一个C#类,可以包含多个级别的多个子级。
手动添加子项看起来像这样:
CustomClass MyClass = new CustomClass(“something”, new List<CustomClass>());
//Level 1
MyClass.Children.Add(“something”, new List<CustomClass>());
//Level 2
MyClass.Children[0].Children.Add(“something”, new List<CustomClass>());
//Level 3
MyClass.Children[0].Children[0].Children.Add(“something”, new List<CustomClass>());
如何使用干净循环来完成此操作?这样做,感觉“不对”:
for (var i = 0; i < 50; i++) {
//Level 1
if (i == 0)
MyClass.Children.Add(“something”, new List<CustomClass>());
//Level 2
if (i == 1)
MyClass.Children[0].Children.Add(“something”, new List<CustomClass>());
//Level 3
if (i == 2)
MyClass.Children[0].Children[0].Children.Add(“something”, new List<CustomClass>());
// and so on up to 50 levels in this case ...
}
重要更新:在每个级别我都需要检查该值是否已经存在,如果不存在,我会添加它。
感谢您的聆听!
我是初学者所以请保持温柔。
答案 0 :(得分:9)
你可以递归地做到:
void FillChildren(CustomClass lastChild, int levels)
{
if(levels > 0)
{
CustomClass child = new CustomClass(“something”, new List<CustomClass>());
FillChildren(child, levels-1);
lastChild.Children.Add(“something”, child);
}
}
您可以这样称呼:
CustomClass MyClass = new CustomClass(“something”, new List<CustomClass>());
FillChildren(MyClass, 50);