返回时,完全停止递归

Ozk*_*kan 9 c# asp.net recursion

我做递归以在List中找到一个具有多个子节点的长值,这些子节点也可以有子节点.

以下方法:

public TaxonomyData getTaxonomyData(long taxId, List<TaxonomyData> TaxonomyTree, TaxonomyData output)
{
    //find taxid in the taxonomy tree list and return the taxonomydata

    foreach (TaxonomyData td in TaxonomyTree)
    {
        if (td.TaxonomyId == taxId)
        {
                output = td;
                //return td; => when doing a return here means I already found a match so it is not necessary to do all the recursion.
        }
        else if (td.Taxonomy.Length > 0)
        {
            getTaxonomyData(taxId, td.Taxonomy.ToList(), output);
        }
    }

    return output;
}
Run Code Online (Sandbox Code Playgroud)

有可能当我这样做return td;(见注释行)我的整个递归停止了吗?

谢谢

Jon*_*eet 15

我怀疑你想要的东西:

public TaxonomyData GetTaxonomyData(long taxId, IEnumerable<TaxonomyData> tree)
{
    foreach (TaxonomyData td in tree)
    {
        if (td.TaxonomyId == taxId)
        {
            return td;
        }
        else
        {
            // See if it's in the subtree of td
            TaxonomyData data = GetTaxonomyData(taxId, td.Taxonomy);
            if (data != null)
            {
                return data;
            }
        }
    }
    // Haven't found it anywhere in this tree
    return null;
}
Run Code Online (Sandbox Code Playgroud)

每个return只返回一个级别,但通过检查else子句中的返回值,当我们找到正确的值时,我们可以一直返回堆栈.

如果尚未找到,则返回给调用者的最终结果将是空引用.

请注意,我已经删除了"输出"参数,因为它是不是这不会是有效的反正ref参数,而并不像清晰刚刚使用的返回值.