jjc*_*pek 1 c# collections tostring parent-child
我有一个类(例如Foo)它覆盖 ToString 方法来打印它的内部状态。这个类有一个集合Foo- 它是子元素。孩子也可以生孩子等等。
我正在寻找在 ToString() 中实现的解决方案,它会自动缩进子元素,例如:
Parent Foo
Child1 Foo
Child1.1 Foo
Child2 Foo
Child2.1 Foo
Child2.2 Foo
Run Code Online (Sandbox Code Playgroud)
解决方法是ToString()仅作为在子树根上调用的“入口点”来输出。该ToString()方法可以调用ToIndentedString(int)将当前缩进级别作为参数的私有方法。然后该方法将返回当前节点在指定缩进处的字符串表示,加上所有子节点在缩进处的字符串表示 + 1 等。
public string ToString()
{
return ToIndentedString(0);
}
private string ToIndentedString(int indentation)
{
StringBuilder result = new StringBuilder();
result.Append(' ', indentation);
result.Append(Environment.NewLine);
foreach (Foo child in children) {
result.Append(child.ToIndentedString(indentation + 1));
}
return result.ToString();
}
Run Code Online (Sandbox Code Playgroud)