繁体   English   中英

如何确定Exception的基类是否为OperationCanceledException?

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

我得到TaskCanceledException

TaskCanceledException

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

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

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

GetType()仅适用于TaskCanceledException GetType().BaseType在这里不可用, IsSubclassOf()也不可用。 而且我不再需要try-catch了。

您有各种可能性:

  • 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
}

ex is OperationCanceledException是最佳选择。

但是,如果您确实需要反射/类型对象,请尝试以下操作:

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

MSDN上的Type.IsAssignableFrom

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM