【发布时间】:2012-03-08 00:31:25
【问题描述】:
有没有办法编写一个 LINQ 风格的“速记”代码来遍历所有级别的 InnerException(s) 抛出的异常?我更愿意将其编写到位,而不是调用扩展函数(如下所示)或继承 Exception 类。
static class Extensions
{
public static string GetaAllMessages(this Exception exp)
{
string message = string.Empty;
Exception innerException = exp;
do
{
message = message + (string.IsNullOrEmpty(innerException.Message) ? string.Empty : innerException.Message);
innerException = innerException.InnerException;
}
while (innerException != null);
return message;
}
};
【问题讨论】:
-
请问您为什么要使用扩展方法以外的东西?您的代码对我来说看起来不错,并且可以在您的代码中的任何地方重用。
-
@ken2k:虽然你不想像他现在那样建立消息......
-
@JeffMercado 是的,但是“扩展方法”的概念有什么问题?
-
@ken2k:说实话,我不太明白你的问题……你刚刚提到代码有缺陷时“看起来很好”。
-
请注意
AggregateExceptions 的行为略有不同。您将不得不走过InnerExceptions属性。这里提供了一个方便的扩展方法:stackoverflow.com/a/52042708/661933 涵盖这两种情况。