如何修复动态对象的InvalidCastException?
ScriptEngine rubyEngine;
//...
dynamic execution_result = rubyEngine.Execute(script, scope);
if (execution_result != null && !silent)
WriteResponce(execution_result.ToString());
此代码生成 InvalidCastException:
无法将“SOMELIB.Graphics”类型的对象转换为类型 'SOMELIB.Object'。
当比较发生时:
执行结果!= null
如果删除此比较,则execution_result.ToString() 会引发相同的异常。
我找到了解决方法:
if (execution_result is SOMELIB.Graphics)
{
SOMELIB.Graphics g = execution_result as SOMELIB.Graphics;
WriteResponce(g.ToString());
return;
}
但我不明白为什么会出现此异常以及如何修复它。
ScriptEngine rubyEngine;
//...
dynamic execution_result = rubyEngine.Execute(script, scope);
if (execution_result != null && !silent)
WriteResponce(execution_result.ToString());
This code generates InvalidCastException:
Unable to cast object of type 'SOMELIB.Graphics' to type
'SOMELIB.Object'.
When the comparison occurs:
execution_result != null
If this comparison is removed, then execution_result.ToString() throws the same exception.
I have found a workaround:
if (execution_result is SOMELIB.Graphics)
{
SOMELIB.Graphics g = execution_result as SOMELIB.Graphics;
WriteResponce(g.ToString());
return;
}
but I don't understand why does this exception appear and how to fix it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将动态转换为对象以避免 DLR(动态语言运行时)尝试将 ToString 方法绑定到其(真正的)动态类类型。
Cast the dynamic to object to avoid the DLR (dynamic language runtime) try bind the ToString method to its (real) dynamic class type.