Why does this conversion doesn't work?

戏子无情 提交于 2019-12-31 02:43:12

问题


following code behaves strange (at least for me):

int testValue = 1234;

this.ConversionTest( testValue );

private void ConversionTest( object value )
{
    long val_1 = (long) (int) value; // works
    long val_2 = (long) value;       // InvalidCastException
}

I don't understand why the direct (explicit) cast to long doesn't work. Can someone explain this behaviour?

Thanks


回答1:


The value parameter of your ConversionTest method is typed as object; this means that any value types -- for example, int -- passed to the method will be boxed.

Boxed values can only be unboxed to exactly the same type:

  • When you do (long)(int)value you're first unboxing value to an int (its original type) and then converting that int to a long.
  • When you do (long)value you're attempting to unbox the boxed int to a long, which is illegal.


来源:https://stackoverflow.com/questions/3666195/why-does-this-conversion-doesnt-work

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