控制递归方法深度——获取所有子文件夹

Mar*_*aro 4 c# recursion .net-3.5

我正在遍历一些共享以获取信息/权限..等我正在使用递归遍历所有子共享。它工作正常,但是,用户应该能够将子共享级别限制为特定数量,这是应用程序中的参数?

private static INodeCollection NodesLookUp(string path)
    {
        var shareCollectionNode = new ShareCollection(path);
        // Do somethings

       foreach (var directory in Directory.GetDirectories(shareCollectionNode.FullPath))
        {
            shareCollectionNode.AddNode(NodesLookUp(directory));

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

这段代码将一直到达最低级别,我怎样才能在特定级别停止它?例如只获得 2 级之前的所有股份?

谢谢。

Ily*_*nov 6

level在每一级递归调用之后传递变量并增加它怎么样?这将允许您控制当前的递归级别或剩余的递归级别。不要忘记检查是否为空。

private const int maxDepth = 2;

private static INodeCollection NodesLookUp(string path, int level)
{
   if(level >= maxDepth)
        return null;

   var shareCollectionNode = new ShareCollection(path);
   // Do somethings

   foreach (var directory in Directory.GetDirectories(shareCollectionNode.FullPath))
   {
       var nodes = NodesLookUp(directory, level + 1);

       if(nodes != null)
            shareCollectionNode.AddNode(nodes);

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

初始级别可以是零索引,例如

NodesLookUp("some path", 0);
Run Code Online (Sandbox Code Playgroud)


Jim*_*hel 5

不要使用全局变量来控制级别,而是maxLevel在每次递归调用时传递 和 递减。

private static INodeCollection NodesLookUp(string path, int maxLevel)
{
    var shareCollectionNode = new ShareCollection(path);
    if (maxLevel > 0)
    {
        foreach (var directory in Directory.GetDirectories(shareCollectionNode.FullPath))
        {
            shareCollectionNode.AddNode(NodesLookup(directory, maxLevel-1));
        }
    }
    return shareCollectionNode;
}
Run Code Online (Sandbox Code Playgroud)