简体   繁体   English

帮助递归和返回值

[英]Help with recursion and returning value

This is an extension of a previously posted question. 这是先前发布的问题的扩展。 I'm trying to recursively build a string. 我试图递归地建立一个字符串。 I need to change the function below to do this - each recursion of the function generates the desired string, but I need to concat these together and return the whole string. 我需要更改下面的函数来执行此操作-函数的每次递归都会生成所需的字符串,但是我需要将它们合并在一起并返回整个字符串。 'related' is passed into the function as an empty string and I thought the way I was using string.Format would append each recursion to the 'related' string? “相关”作为一个空字符串传递到函数中,我认为我使用string.Format的方式会将每个递归追加到“相关”字符串上吗? Apparently not. 显然不是。

Not sure how... 不确定如何...

private string getRelatedNews(Taxonomy taxData, string related, string contentTitle)
{
    foreach (TaxonomyItemData item in taxData.TaxonomyItems)
        {
            if (taxData.TaxonomyName.Equals(contentTitle) && taxData.TaxonomyItemCount != 0)
            {
                related = string.Format("{0}<li><a href='{1}'\">{2}</a></li>", related, item.Link, item.Name);
            }                   
        }
    // Show all its sub categories
    foreach (TaxonomyData cat in taxData.Taxonomy)
        {   
            getRelatedNews(cat, related, contentTitle);
        }

    return(related);

}
foreach (TaxonomyData cat in taxData.Taxonomy)
    {   
        getRelatedNews(cat, related, contentTitle);
    }

should be 应该

foreach (TaxonomyData cat in taxData.Taxonomy)
    {   
        related = getRelatedNews(cat, related, contentTitle);
    }

because strings are immutable. 因为字符串是不可变的。

Well try this... 好吧试试这个...

related = getRelatedNews(cat, related, contentTitle);

I am not sure about your logic and flow of the program... then also I think recursive function must be called like this.... 我不确定您的程序逻辑和流程...然后我还认为必须这样调用递归函数....

private string getRelatedNews(Taxonomy taxData, string related, string contentTitle)
{
    foreach (TaxonomyItemData item in taxData.TaxonomyItems)
        {
            if (taxData.TaxonomyName.Equals(contentTitle) && taxData.TaxonomyItemCount != 0)
            {
                related = string.Format("{0}<li><a href='{1}'\">{2}</a></li>", related, item.Link, item.Name);
            }                   
        }
    // Show all its sub categories
    foreach (TaxonomyData cat in taxData.Taxonomy)
        {   
            related = getRelatedNews(cat, related, contentTitle);
        }

    return(related);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM