递归方法不会循环孩子的孩子

时间:2017-02-28 13:18:29

标签: c# asp.net recursion

我正在尝试创建一个递归方法来创建菜单。 我想要实现的菜单显示了孩子们的孩子等等。 我调试了代码,它一直到“最小的孩子”。

public string GetMenu(Node currentPage)
    {
        StringWriter stringWriter = new StringWriter();
        using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
        {

        foreach (var item in currentPage.ChildrenAsList)
        {
            writer.RenderBeginTag(HtmlTextWriterTag.Li);
            writer.AddAttribute(HtmlTextWriterAttribute.Href, item.Url);
            writer.RenderBeginTag(HtmlTextWriterTag.A);
            writer.Write(item.Name);


            if (item.ChildrenAsList.Any())
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Ul);
                GetMenu(new Node(item.Id));
                writer.RenderEndTag();
            }
            writer.RenderEndTag();
            writer.RenderEndTag();
        }
    }
    return stringWriter.ToString();
}

此方法提供输出:

<ul class="nav nav-sidebar">

    <li>
    <a href="/artikelsida001/">Artikelsida001
    <ul>

    </ul>
    </a></li>
    <li><a href="/patrikartikelsida/">PatrikArtikelsida
    <ul>

    </ul>
    </a></li>
    <li><a href="/en-testsida/">En testsida</a></li>
    </ul>

1 个答案:

答案 0 :(得分:4)

每次拨打GetMenu时,您都会创建一个新的StringWriter - 但是您忽略了递归调用的返回值。最简单的修复可能是将其更改为:

public string GetMenu(Node currentPage)
{
    var stringWriter = new StringWriter();
    using (var htmlWriter = new HtmlTextWriter(stringWriter))
    {
        RenderMenu(currentPage, writer);
    }
    return stringWriter.ToString();
}

private void RenderMenu(Node node, HtmlTextWriter writer)
{
    // Mostly copied from the code in the question...
    foreach (var item in currentPage.ChildrenAsList)
    {
        writer.RenderBeginTag(HtmlTextWriterTag.Li);
        writer.AddAttribute(HtmlTextWriterAttribute.Href, item.Url);
        writer.RenderBeginTag(HtmlTextWriterTag.A);
        writer.Write(item.Name);

        if (item.ChildrenAsList.Any())
        {
            writer.RenderBeginTag(HtmlTextWriterTag.Ul);
            // Note the change here
            RenderMenu(new Node(item.Id), writer));
            writer.RenderEndTag();
        }
        writer.RenderEndTag();
        writer.RenderEndTag();
    }
}

请注意递归现在如何使用同一作者调用RenderMenu