gpt4 book ai didi

c# - 递归方法检查的最后一次迭代

转载 作者:行者123 更新时间:2023-12-02 01:18:41 25 4
gpt4 key购买 nike

我有一个递归方法,可以构建资源及其相关资源的树状结构。

对于我使用的每个资源,我都会将其添加到一个类成员列表中,我会在每次迭代时检查该列表,以确保我们不会在相互依赖的资源上无限循环。

每次第一次调用这个递归方法,都需要类成员列表清楚。

目前我有一个单独的方法来执行此操作,我可以在对递归方法的调用之间调用它。

我想去掉这个方法调用,每次都自动重置列表。

目前我可以看到两个选项来解决这个问题:

  1. 测试调用方法是否与当前相同执行方法,如果没有,则重置列表
  2. 取而代之的是摆脱递归和排队项目,出队和我们去排队。在方法调用结束时,我可以重置列表。

您将如何着手解决这个问题?你会采取什么方法?

这是我的代码目前的样子:

public class GetAllRelatedResourcesByParentGuidQuery : IGetAllRelatedResourcesByParentGuidQuery
{
private readonly IList<Guid> _itemsCheckedForRelations = new List<Guid>();

public IEnumerable<IDependency> Invoke(Guid parentCiId,
IResoucesByIdQuery getResources)
{
if (!_itemsCheckedForRelations.Contains(parentCiId))
{
var relatedResources = getResources.Invoke(parentCiId);

_itemsCheckedForRelations.Add(parentCiId);

if (relatedResources.Count() > 0)
{
foreach (var relatedResource in relatedResources)
{
relatedResource.Resource.DependentResources = Invoke(
relatedResource.Resource.Id,
getResources);

yield return relatedResource;
}
}
}
}

public void ResetCheckedItemsCollection()
{
_itemsCheckedForRelations.Clear();
}
}

最佳答案

我会创建一个执行创建的公共(public)方法,但不关心递归方法,并将其作为参数。

public List<string> DoSomething(int input)
{
List<string> results = new List<string>();
DoSomethingImpl(input, results);
return results;
}

private void DoSomethingImpl(int input, List<T> results)
{
// For example...
if (input == 0)
{
return results;
}
results.Add("Foo");
DoSomethingImpl(input - 1, results);
}

关于c# - 递归方法检查的最后一次迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7835945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com