Why does this conversion doesn't work?
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 beha开发者_高级运维viour?
Thanks
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)valueyou're first unboxingvalueto anint(its original type) and then converting thatintto along. - When you do
(long)valueyou're attempting to unbox the boxedintto along, which is illegal.
加载中,请稍侯......
精彩评论