由Recursion引起的StackOverflowException

Omn*_*Owl 6 c# stack-overflow recursion

我目前正在编写一个程序来帮助编写Lore.每个图书对象都可以是父母并且有孩子.这意味着每个孩子都可以有孩子等无限.我正在使用ToString()方法,可以使用递归来解决这个问题,但我不断得到StackOverflowException.

我知道这意味着什么,但我对如何解决这个问题表示怀疑.我是C#的新手,但有很多Java经验,所以如果你知道一些我错过的技巧或者其他东西,请告诉我!

所以我的问题是:如何避免StackOverflow异常?问题出在GetAllChildren()

编辑:

运行测试后,我应该得到这样的东西:

Name: a
Children:
b
c
    d
e
Run Code Online (Sandbox Code Playgroud)

使用@lc的代码.我得到以下输出:

Name: a
Children: No Children   b
c
e
    b
c
e
    b
c
e
Run Code Online (Sandbox Code Playgroud)

这是班级:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

lc.*_*lc. 8

我想你的意思是:

if (book.isParent)
{
    foreach (var child in book.Children)
        GetAllChildren(child, sb);
}
Run Code Online (Sandbox Code Playgroud)

否则你只是反复调用GetAllChildren具有相同参数(book, sb)的方法.


旁注 - 你仍然有一些问题,因为GetAllChildren正在迭代通过子节点的停止条件,当它不应该(如果它不是父节点,它不应该有子节点).它应该返回自己的名称.此外,每个孩子还应在上面的foreach循环中附加其名称(实际上,每本书都应附加自己的名字).

附注2 - 编写的方法(带有这些更改)应该是静态的,因为它与任何给定的实例无关(这使我得到下面的建议).


建议 - 我会推荐类似下面的东西(未经测试,需要对格式化工作):

//name changed to reflect what it really does
//also changed to be an instance method (we no longer pass in a Book)
//added listThisBooksName parameter to allow supressing the topmost book's output
private void AppendAllChildren(StringBuilder sb, int level = 0, 
    bool listThisBooksName = false)
{
    if (listThisBooksName)
    {
        //append ourself here

        //first indent however far we need to
        sb.Append(new String('\t', level));

        //now add our name
        sb.Append(this.Name);

        //and a newline (you can strip the last one later if you want)
        sb.Append('\n');
    }

    //forget the "isParent" property, just check if it has any children
    //we don't need Children.Any() because the foreach will just iterate 0 times
    //you might also consider using a List<Book> instead of an array for Children
    if (this.Children != null)
        foreach (var child in this.Children)
            child.AppendAllChildren(sb, level+1, true);
}
Run Code Online (Sandbox Code Playgroud)