Why does this cast from short to int fail?

给你一囗甜甜゛ 提交于 2019-12-04 23:53:51

What you have in your hands is an instance of unboxing. Specifically when unboxing, you can only unbox to the type of the value that was originally boxed; if that type is A and you are unboxing to B, it does not matter if an implicit conversion from A to B exists (the unboxing will still fail).

See Eric Lippert's classic blog post on the subject for an involved explanation.

You have to cast to the very specific type since you are unboxing - the problem is that oReader["Duration"] returns an object instance:

short myShort = 42;
object o = myShort;
int myInt = (int)o; //fails

It will succeed if you cast back to short first, then to int:

(int) (short) oReader["Duration"]
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!