2017-08-29 35 views
1

我得到一個TaskCanceledException如何找出Exception的基類是否爲OperationCanceledException?

TaskCanceledException

然後,我通過這個例外,因爲Exception到另一種方法。如果我檢查類型

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

他不會介入此if子句。我如何檢查異常的基本類型是否爲OperationCanceledException

GetType()只適用於TaskCanceledExceptionGetType().BaseType在這裏不可用,也不是IsSubclassOf()。我現在不在try-catch了。

+1

'ex is OperationCanceledException' should work –

+1

您是否試過簡單的'if(ex是OperationCanceldException)'?你甚至可以在一個語句中投射它:'if(ex是OperationCanceldException ocex)' – Fildor

+0

Type.BaseType可能是你需要的。這個屬性返回你的對象所在的類型。 – Kinxil

回答

4

你有不同的possiblities:

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

除了'IsAssignableFrom'之外的其他應該在'Xamarin.Forms'中工作。 – testing

3

ex is OperationCanceledException是最好的選擇。

但如果你真的需要反思/類型的對象,試試這個:

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

Type.IsAssignableFrom on MSDN

+0

感謝您的回覆。可悲的是'IsAssignableFrom'似乎不能在'Xamarin.Forms'中找到... – testing

+0

你嘗試過'is/as'運算符嗎? – hmnzr

+0

或者在Xamarin上下文中嘗試'ex.GetTypeInfo()。IsAssignableFrom' – hmnzr

相關問題