如何判断 Exception 的 base class 是否为 OperationCanceledException?

How to find out if base class of Exception is OperationCanceledException?

我得到一个 TaskCanceledException:

然后我将此异常作为 Exception 传递给另一个方法。如果我检查类型

if (ex.GetType() == typeof(OperationCanceledException))
    // ...

他没有进入这个 if 子句。如何检查异常的基类型是否为 OperationCanceledException?

GetType() 仅适用于 TaskCanceledExceptionGetType().BaseType 在这里不可用,IsSubclassOf() 也不可用。我不在 try-catch 了。

ex is OperationCanceledException 是最好的选择。

但如果你真的需要 reflection/type 对象,试试这个:

typeof(OperationCanceledException).IsAssignableFrom(ex.GetType())

Type.IsAssignableFrom on MSDN

你有多种可能性:

  • is 运算符:

    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
}