有什么方法可以编写 LINQ 样式的“速记”代码来遍历抛出异常的所有级别的 InnerException 吗?我更愿意就地编写它,而不是调用扩展函数(如下所示)或继承 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;
}
};
最佳答案
不幸的是,LINQ 不提供可以处理层次结构的方法,只提供集合。
我实际上有一些扩展方法可以帮助做到这一点。我手头没有确切的代码,但它们是这样的:
// all error checking left out for brevity
// a.k.a., linked list style enumerator
public static IEnumerable<TSource> FromHierarchy<TSource>(
this TSource source,
Func<TSource, TSource> nextItem,
Func<TSource, bool> canContinue)
{
for (var current = source; canContinue(current); current = nextItem(current))
{
yield return current;
}
}
public static IEnumerable<TSource> FromHierarchy<TSource>(
this TSource source,
Func<TSource, TSource> nextItem)
where TSource : class
{
return FromHierarchy(source, nextItem, s => s != null);
}
那么在这种情况下,您可以这样做来枚举异常:
public static string GetaAllMessages(this Exception exception)
{
var messages = exception.FromHierarchy(ex => ex.InnerException)
.Select(ex => ex.Message);
return String.Join(Environment.NewLine, messages);
}
关于c# - 从 InnerException 获取所有消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9314172/