C#递归函数详细介绍及使用方法

2019-12-30 11:57:11于丽


我曾经想写关于匿名递归方法的文章,但是我发觉我的解释无法超越那篇文章。 
5. 查找文件 
C#,递归函数,C#递归函数
我在供你下载的示范项目中使用了递归,通过这个项目你可以搜索某个路径,并获得当前文件夹和其子文件夹中所有文件的路径。 
复制代码
private Dictionary<string, string> errors = new Dictionary<string, string>(); 
private List<string> result = new List<string>(); 
private void SearchForFiles(string path) 

try 

foreach (string fileName in Directory.GetFiles(path))//Gets all files in the current path 

result.Add(fileName); 

foreach (string directory in Directory.GetDirectories(path))//Gets all folders in the current path 

SearchForFiles(directory);//The methods calls itself with a new parameter, here! 


catch (System.Exception ex) 

errors.Add(path, ex.Message);//Stores Error Messages in a dictionary with path in key 


这个方法似乎不需要满足任何条件,因为每个目录如果没有子目录,会自动遍历所有子文件。

总结 
我们其实可以用递推算法来替代递归,且性能会更好些,但我们可能需要更多的时间开销和非递归函数。但关键是我们必须根据场景选择最佳实现方式。