关于拆箱装箱引发的类型转换报错

异常:System.InvalidCastException: Specified cast is not valid.

拆箱检查确切类型,如文档中所述:

拆箱是从类型对象到值类型或从接口类型到实现接口的值类型的显式转换。拆箱操作包括:

  • 检查对象实例以确保它是给定值类型的盒装值

  • 将实例中的值复制到value-type变量中

第一步是检查对象实例是否与目标类型匹配。

同样引用文档:

For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. Attempting to unbox null causes a NullReferenceException. Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.

posted @ 2021-07-07 11:03  何文西  阅读(71)  评论(0编辑  收藏  举报