2

让我们假设一个特定的异常“ SomeException”是异常堆栈的一部分,

所以让我们假设ex.InnerException.InnerException.InnerException它的类型是“ SomeException

C# 中是否有任何内置 API 会尝试在异常堆栈中定位给定的异常类型?

例子:

SomeException someExp = exp.LocateExceptionInStack(typeof(SomeException));
4

2 回答 2

6

不,我不相信有任何内置的方法可以做到这一点。不过不难写:

public static T LocateException<T>(Exception outer) where T : Exception
{
    while (outer != null)
    {
        T candidate = outer as T;
        if (candidate != null)
        {
            return candidate;
        }
        outer = outer.InnerException;
    }
    return null;
}

如果您使用的是 C# 3,则可以将其设为扩展方法(只需将参数设为“this Exception outer”),使用起来会更好:

SomeException nested = originalException.Locate<SomeException>();

(请注意名称的缩写 - 根据您自己的口味调整:)

于 2009-03-19T11:33:08.627 回答
1

它只有 4 行代码:

    public static bool Contains<T>(Exception exception)
        where T : Exception
    {
        if(exception is T)
            return true;

        return 
            exception.InnerException != null && 
            LocateExceptionInStack<T>(exception.InnerException);
    }
于 2009-03-19T11:34:08.500 回答