【发布时间】:2018-05-12 05:46:58
【问题描述】:
方法签名:
public static string TraverseList(string prefix, object list)
输入:
prefix: "Boo"
list: new object[] { "a string", new[] { "a", "b", "c" }, "spam", new[] { "eggs" }, new[] { new[] { "one", "two" }, new[] { "three", "four" } } }
预期输出:
Boo.0: a string
Boo.1.0: a
Boo.1.1: b
Boo.1.2: c
Boo.2: spam
Boo.3.0: eggs
Boo.4.0.0: one
Boo.4.0.1: two
Boo.4.1.0: three
Boo.4.1.1: four
我尝试实现这一点:
public static string TraverseList(string prefix, object list)
{
int index = 0;
int index1 = 0;
int index2 = 0;
StringBuilder dumpListBuilder = new StringBuilder();
if (list is Array)
{
foreach (var obj in (Array)list)
{
if (obj is Array)
{
foreach (var obj1 in (Array)obj)
{
if (obj1 is Array)
{
foreach (var obj2 in (Array)obj1)
{
dumpListBuilder.AppendFormat("{0}.{1}.{2}.{3}: {4}{5}", prefix, index, index1, index2, obj2, Environment.NewLine);
index2++;
}
}
else
{
dumpListBuilder.AppendFormat("{0}.{1}.{2}: {3}{4}", prefix, index, index1, obj1, Environment.NewLine);
}
index1++;
index2 = 0;
}
}
else
{
dumpListBuilder.AppendFormat("{0}.{1}: {2}{3}", prefix, index, obj, Environment.NewLine);
}
index++;
index1 = 0;
}
}
return dumpListBuilder.ToString();
}
它有效,但效率不高,并且仅限于 3 个嵌套列表的深度。任何人都可以提出无限深度的最佳解决方案吗?
我知道我应该使用递归,但是如何在不更改方法签名的情况下做到这一点?
【问题讨论】:
-
提示:递归
-
您无法更改原始转储列表签名,但您可以创建一个可以从 DumpList 调用并从其自身递归调用的进一步方法,不是吗?
-
@Gian Paolo 不需要任何进一步的方法
-
对@SirRufo,我没有注意到您可以处理在每个递归级别更改它的前缀