我得到一个TaskCanceledException
:
然后我将此异常作为 Exception
传递给另一个方法。如果我检查类型
if (ex.GetType() == typeof(OperationCanceledException))
// ...
他没有进入这个 if 子句。如何检查异常的基类型是否为 OperationCanceledException
?
GetType()
仅适用于 TaskCanceledException
。
GetType().BaseType
在这里不可用,IsSubclassOf()
也不可用。而且我不再在 try-catch
中了。
最佳答案
你有多种可能性:
is
运算符(operator):if (ex is OperationCancelledException)
as
运算符(如果您想进一步使用异常):OperationCancelledException opce = ex as OperationCancelledException; if (opce != null) // will be null if it's not an OperationCancelledException
反射
IsAssignableFrom
(但评论说在 Xamarin 中不起作用):if (typeof(OperationCancelledException).IsAssignableFrom(ex.GetType())
在 C#7 中,您可以进行模式匹配:
if (ex is OperationCancelledException opce)
{
// you can use opce here
}
关于c# - 如何确定异常的基类是否为 OperationCanceledException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45940638/