2011-08-08 94 views
1
ScriptEngine rubyEngine; 
//... 
dynamic execution_result = rubyEngine.Execute(script, scope); 

if (execution_result != null && !silent) 
    WriteResponce(execution_result.ToString()); 

此代碼生成InvalidCastException的如何修復動態對象的InvalidCastException?

無法轉換類型的對象 'SOMELIB.Graphics' 到類型 'SOMELIB.Object'。

當比較發生:

execution_result = NULL

如果該比較被移除,然後execution_result.ToString()拋出相同的異常。

我已經找到了解決辦法:

if (execution_result is SOMELIB.Graphics) 
{ 
    SOMELIB.Graphics g = execution_result as SOMELIB.Graphics; 
    WriteResponce(g.ToString()); 
    return; 
} 

,但我不明白爲什麼會發生這種異常出現,如何解決它。

+0

嗯,奇怪的是,它試圖投射到SOMELIB.Object而不是System.Object –

+0

正確。問題在於動態類型。如果我將動態類型轉換爲對象類型,ToString()將起作用:object execution_result_obj = execution_result as object; – Dmitriy

回答

0

將動態轉換爲對象以避免DLR(動態語言運行庫)嘗試將ToString方法綁定到其(真實)動態類類型。

ScriptEngine rubyEngine; 
//... 
dynamic execution_result = rubyEngine.Execute(script, scope); 

object result = execution_result as object; 
if (result != null && !silent) 
    WriteResponce(result.ToString());