我正在寻找一种更好的方法来递归可能具有循环依赖关系的项目。目前,我传递了一个已处理项目的列表,以便不再处理它们,但这可能不是最好的方法。
这是我目前正在做的事情:
/// <summary>
/// caching dependencies in order to increase performance
/// </summary>
private static readonly IDictionary<string, IEnumerable<OwnedItem>> dependencies
= new Dictionary<string, IEnumerable<OwnedItem>>();
/// <summary>
/// recursively find OwnedItem this oi depends upon
/// in order to correctly handle cyclic dependencies, already considered
/// dependencies need to be supplied as well (can be null or empty)
/// </summary>
/// <param name="oi"></param>
/// <param name="parentDeps"></param>
/// <returns></returns>
private static IEnumerable<OwnedItem> GetDependencies(
OwnedItem oi,
IEnumerable<OwnedItem> parentDeps)
{
if (null == oi)
{
return Enumerable.Empty<OwnedItem>();
}
if (dependencies.ContainsKey(oi.UniqueId))
{
return dependencies[oi.UniqueId];
}
var comparer = new TCObjectComparer<OwnedItem>();
var result = new HashSet<OwnedItem>(comparer);
result.Add(oi);
result.UnionWith(parentDeps ?? Enumerable.Empty<OwnedItem>());
foreach (var oi2 in oi.AllUsedOwnedItemsToBeIncluded.Except(
result, comparer))
{
result.UnionWith(GetDependencies(oi2, result));
}
dependencies[oi.UniqueId] = result;
return result;
}
这些项目属于“OwnedItem”类型,并IEnumerable<OwnedItem>
在属性中保留其直接依赖项的列表(),AllUsedOwnedItemsToBeIncluded
但基本上只要“项目”保留可能发生循环依赖的“项目”列表,这应该适用。使用字典只是避免多次进行相同的计算;这不是必需的。此外,只需要一个 的实例TCObjectComparer
,但这也不是必需的。有什么建议么?我认为必须存在一些经典算法来处理这个问题,但我找不到它。