我正在通过一些共享来获取信息/权限。等我用递归遍历所有子共享。它工作得很好,然而,用户应该能够将子共享级别限制为特定的数字,这是应用程序中的一个参数?
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;
}
这段代码会一直到最低级别,我怎么能在特定级别停止它?例如,得到所有的股份,直到2级?
谢谢。
如何传递level
变量并在每一级递归调用后增加它?这将允许您控制当前的递归级别或剩余的递归级别。别忘了检查null
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;
}
初始级别可以为零索引,如
NodesLookUp("some path", 0);
不是使用全局变量来控制级别,而是在每次递归调用时传递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;
}
这个呢:
private static INodeCollection NodesLookUp(string path, Int32 currentLevel, Int32 maxLevel)
{
if (currentLevel > maxLevel)
{
return null;
}
var shareCollectionNode = new ShareCollection(path);
// Do somethings
foreach (var directory in Directory.GetDirectories(shareCollectionNode.FullPath))
{
INodeCollection foundCollection = NodesLookUp(directory, currentLevel + 1, maxLevel)
if(foundCollection != null)
{
shareCollectionNode.AddNode();
}
}
return shareCollectionNode;
}
在这种情况下,您不必担心每次方法运行时私有字段的状态被修改。而且,只要剩下的代码是线程安全的,它就会是线程安全的。