c# - 如何确定异常的基类是否为 OperationCanceledException?

标签 c# inheritance exception xamarin.forms

我得到一个TaskCanceledException:

TaskCanceledException

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

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

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

GetType() 仅适用于 TaskCanceledExceptionGetType().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/

相关文章:

C# 和指向成员的指针

python - Python中的描述符类设计(带继承)

c++ - 奇怪的无序 map 情况

java.lang.IllegalStateException : Cannot forward after response has been committed in servlet 错误

c++ - 来自继承类的 Makefile 错误

c# - 如何捕获使用 MethodInfo.Invoke 调用的方法中抛出的异常?

c# - Linq 查询 Where() SQL % 等效

c# - LINQ 比较两个列表并删除

c# - ASP.net LINQ : return items where id equals a variable

java - 泛型和扩展的问题