2011-08-08 2 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

흠, 홀수로 System.Object 대신 SOMELIB.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());