我目前正在编写一个程序来帮助编写 Lore。每个书本对象都可以是父母并有孩子。这意味着每个孩子都可以有孩子等等。我正在研究一个 ToString() 方法,该方法可以使用递归来解决这个问题,但我不断收到 StackOverflowException。
我知道这意味着什么,但我怀疑如何解决它。我是 C# 的新手,但有很多 Java 经验,所以如果你知道一个技巧或我错过的东西,请告诉我!
所以我的问题是:如何避免 StackOverflow 异常?问题出在 GetAllChildren()
编辑:
运行测试后,我应该得到如下信息:
Name: a
Children:
b
c
d
e
使用来自@lc 的代码。我得到以下输出:
Name: a
Children: No Children b
c
e
b
c
e
b
c
e
这是课程:
class Book
{
private String name;
private Book[] children;
private StringBuilder text;
private Boolean isParent;
public Book(String name, Book[] children, StringBuilder text, Boolean isParent)
{
this.name = name;
this.children = children;
this.text = text;
this.isParent = isParent;
}
/**
* Most likely all possible Constructors
* */
public Book(String name, Book[] children) : this(name, children, new StringBuilder("No Text"), true) { }
public Book(String name, String text) : this(name, new Book[0], new StringBuilder(text), false) { }
public Book(String name, StringBuilder text) : this(name, new Book[0], text, false) { }
public Book(String name) : this(name, new Book[0], new StringBuilder("No Text"), false) { }
public Book(Book[] children, String text) : this("Unnamed Book", children, new StringBuilder(text), true) { }
public Book(Book[] children, StringBuilder text) : this("Unnamed Book", children, text, true) { }
public Book(Book[] children) : this("Unnamed Book", children, new StringBuilder("No Text"), true) { }
public Book(StringBuilder text) : this("Unnamed Book", new Book[0], text, false) { }
public Book() : this("Unnamed Book", new Book[0], new StringBuilder("No Text"), false) { }
public String Name
{
get { return name; }
set { name = value; }
}
public Book[] Children
{
get { return children; }
set { children = value; }
}
/**
* Will Return the StringBuilder Object of this Text
* */
public StringBuilder Text
{
get { return text; }
set { text = value; }
}
public Boolean IsParent
{
get { return isParent; }
set { isParent = value; }
}
private void GetAllChildren(Book book, StringBuilder sb)
{
if (book.isParent)
{
GetAllChildren(book, sb);
}
else
{
sb.Append("\t");
foreach (Book b in children)
{
sb.Append(b.Name + "\n");
}
}
}
public override String ToString()
{
StringBuilder sChildren = new StringBuilder("No Children");
if (children.Length != 0)
{
GetAllChildren(this, sChildren);
}
return "Name: " + name + "\n" +
"Children: " + sChildren.ToString();
}
}