我希望能够捕捉到 WebFaultException<string>
作为最具体的然后是WebFaultException<T>
(T 是任何其他类型)作为更一般的情况来处理。这可能吗?
try
{
// throw exception
}
catch (WebFaultException<string> e)
{
// handle more specific type
}
catch (WebFaultException<T> e)
{
// handle more general type
}
catch (Exception e)
{
}
最佳答案
正如其他答案所提到的;您不能直接指定捕获每个 WebFaultException<T>
既不知道指定的类型参数,也不知道它的基类型。
但是,如果您想要捕获所有 WebFaultException
出现并根据泛型类型以不同方式处理响应,那么您可以简单地捕获基类型并使用反射来确定泛型参数的类型,使用 Type.GetGenericArguments()
.这是一个简单的 catch
子句来展示你可以如何去做:
// ...
catch (FaultException ex)
{
Type exceptionType = ex.GetType();
if (exceptionType.IsGenericType)
{
// Find the type of the generic parameter
Type genericType = ex.GetType().GetGenericArguments().FirstOrDefault();
if (genericType != null)
{
// TODO: Handle the generic type.
}
}
}
如果你想要一个更深入的例子,我已经上传了一个测试程序来演示这个到PasteBin .随便看看吧!
关于c# - 你能在 T 是任何类型的地方捕获异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9029942/