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

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


if (counter <= 0) 
Console.WriteLine(partialOutput); 
else 

BooleanCompositions(counter - 1, partialOutput+ ", true"); 
BooleanCompositions(counter - 1, partialOutput+ ", false"); 


4. 获取内部异常 
如果你想获得innerException,那就选择递归方法吧,它很有用。 
复制代码
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);