Trying to cast a boxed int to byte

后端 未结 2 1939
轻奢々
轻奢々 2021-01-18 03:05

Code to illustrate :

        int i = 5;
        object obj = i;
        byte b = (byte)obj; // X

When run, this generates a System.InvalidC

2条回答
  •  悲哀的现实
    2021-01-18 03:51

    MSDN explicitly says that unboxing to a different type will throw an InvalidCastException.

    My understanding is that the type to which a variable is unboxed is actually a parameter to the underlying CIL assembly command. It is unbox opcode that actually throws the InvalidCastException.

    InvalidCastException is thrown if the object is not boxed as valType.

提交回复
热议问题