我目前正在編寫一個程序來幫助寫Lore。每個書對象都可以是父母並且有孩子。這意味着每個孩子都可以有孩子等無限。我正在處理一個ToString()方法,它可以使用遞歸來解釋這個問題,但我一直在收到一個StackOverflowException。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();
}
}
通過在'stackoverflow.com查詢 – 2013-03-14 09:15:37
@SiGanteng我正在考慮做笑話,但我不選擇; P – OmniOwl 2013-03-14 09:16:29
在'isParent'分支內調用'GetAllChildren(book,sb)'後面的想法是什麼? ?請注意,'book'和'sb'都沒有被改變。 – 2013-03-14 09:19:03