要在@Anthony Pegram的回答跟进,你可以定义一个扩展方法来获取内部异常的序列:
public static class ExceptionExtensions
{
public static IEnumerable<Exception> GetAllExceptions(this Exception ex)
{
List<Exception> exceptions = new List<Exception>() {ex};
Exception currentEx = ex;
while (currentEx.InnerException != null)
{
currentEx = currentEx.InnerException;
exceptions.Add(currentEx);
}
return exceptions;
}
}
那么你就可以使用LINQ的序列。如果我们有一个抛出嵌套异常这样的方法:
public static class ExceptionThrower {
public static void ThisThrows() {
throw new Exception("ThisThrows");
}
public static void ThisRethrows() {
try {
ExceptionThrower.ThisThrows();
}
catch (Exception ex) {
throw new Exception("ThisRetrows",ex);
}
}
}
这里是你如何使用LINQ与我们创建的小扩展方法:
try {
ExceptionThrower.ThisRethrows();
}
catch(Exception ex) {
// using LINQ to print all the nested Exception Messages
// separated by commas
var s = ex.GetAllExceptions()
.Select(e => e.Message)
.Aggregate((m1, m2) => m1 + ", " + m2);
Console.WriteLine(s);
}
由于LINQ工作在序列你必须建立你自己的函数返回一系列异常,然后使用LINQ。 查找'yield'关键字。 –
谢谢,类似Anthony Pegram的回答。但我的代码不会更简洁,如果我使用yield:( – sergtk