将int []转换为object [] [英] Casting int[] to object[]

查看:100
本文介绍了将int []转换为object []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个问题:为什么不可能将 int [] 强制转换为 object [] ,例如
object [] o = new int [] {0,1,2};

I encountered with question: why it's impossible cast int[] to object[] , e.g. object[] o = new int[] { 0, 1, 2 };

同时我可以强制转换为 object 并返回至 int []

Meanwhile I can cast to just object and back to int[].

我很高兴听到深入的答案。

I'll be glad to hear deep answer.

推荐答案

直接来自文档


数组协方差不会特别扩展到值类型数组。例如,不存在允许将int []视为对象[]的转换。

Array covariance specifically does not extend to arrays of value-types. For example, no conversion exists that permits an int[] to be treated as an object[].

整数或任何整数的数组其他值类型不是对象数组。值类型具有与引用类型不同的存储特性。 (引用类型)对象的数组包含对象引用的列表(对象本身位于堆中),因此插槽将始终为恒定宽度。另一方面,值类型将其值直接存储在数组中,因此插槽可以是任意宽度。

An array of ints or any other value-type is not an array of objects. Value types have different storage characteristics to those of reference types. An array of (reference type) objects holds a list of object references (with the objects themselves living in the heap), so the slots will always be a constant width. Value types, on the other hand, store their value directly in the array, so the slots might be any width. This makes a conversion between the two meaningless.

这有点混乱,因为即使值类型是从System.Object派生的,它们的行为也与引用类型非常不同,并且值类型的类似对象的行为(例如装箱)只有通过编译器和运行时对其进行神奇的处理才能实现,并且不会扩展到数组。

It's a little confusing because even though value-types are derived from System.Object, they behave very differently to reference types, and object-like behaviour of value types (e.g. boxing) is only possible through magical handling of them by the compiler and runtime, and it doesn't extend to arrays.

附带说明,强制转换数组是一种很好的躲避行为。我不会做。

As a side note, casting arrays is a well dodgy practice. I wouldn't do it.

这篇关于将int []转换为object []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆