我有一个递归函数,可以从数据库中读取文档的“目录”。 我想用反射(reflect)项目在树中位置的文档打印编号,例如
1. First item,
1.1 Child of first item,
1.1.1 Child of child of first item,
1.2 Child of first item,
2. Second item,
2.1 Child of second item,
等等
目前对此感到很困惑 - 请帮忙?
最佳答案
查看您的代码会很有用。假设数据以某种分层表示形式存储,递归的结构可能如下所示:
void PrintTOC(string prefix, List<Sections> sections) {
// Iterate over all sections at the current level (e.g. "2")
for(int i = 0; i<sections.Length; i++) {
// Get prefix for the current section (e.g. "2.1")
string num = String.Format("{0}.{1}", prefix, i+1);
// Write the current section title
Console.WriteLine("{0} {1}", num, sections[i].Titles);
// Recursively process all children, passing "2.1" as the prefix
if (sections[i].Children != null)
PrintTOC(num, sections[i].Children);
}
}
这保留了一个包含父部分索引的prefix 参数。当前部分中的所有数字都附加在此前缀之后。
关于c# - 递归函数的顺序编号?例如2, 2.1, 2.1.1, 2.2, 2.2.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2668007/