要在@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