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


public Exception GetInnerException(Exception ex)
{
return (ex.InnerException == null) ? ex : GetInnerException(ex.InnerException);
}


为什么要获得最后一个innerException呢?!这不是本文的主题,我们的主题是如果你想获得最里面的innerException,你可以靠递归方法来完成。
这里的代码:

复制代码 代码如下:


return (ex.InnerException == null) ? ex : GetInnerException(ex.InnerException);


与下面的代码等价

复制代码 代码如下:


if (ex.InnerException == null)//限制条件
return ex;
return GetInnerException(ex.InnerException);//用内部异常作为参数调用自己


现在,一旦我们获得了一个异常,我们就能找到最里面的innerException。例如:

复制代码 代码如下:


try
{
throw new Exception("This is the exception",
new Exception("This is the first inner exception.",
new Exception("This is the last inner exception.")));
}
catch (Exception ex)
{
Console.WriteLine(GetInnerException(ex).Message);
}


我曾经想写关于匿名递归方法的文章,但是我发觉我的解释无法超越那篇文章。
5. 查找文件

Proj1


我在供你下载的示范项目中使用了递归,通过这个项目你可以搜索某个路径,并获得当前文件夹和其子文件夹中所有文件的路径。

复制代码 代码如下:


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
}
}


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

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

James MaCaffrey博士认为尽量不要使用递归,除非实在没有办法。你可以读一下他的文章。
我认为
A) 如果性能是非常重要的,请避免使用递归
B)如果递推方式不是很复杂的,请避免使用递归
C) 如果A和B都不满足,请不要犹豫,用递归吧。
例如
第一节(阶乘):这里用递推并不复杂,那么就避免用递归。
第二节(Fibonacci):像这样的递归并不被推荐。
当然,我并不是要贬低递归的价值,我记得人工智能中的重要一章有个极小化极大算法(Minimax algorithm),全部是用递归实现的。
但是如果你决定使用队规方法,你最好尝试用存储来优化它。
版权声明:本文由作者Tony Qu原创, 未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则视为侵权。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjdjpp.html