3

I have the following method

private void AM(object[] x)
{
}

When we call it like this:

int[] x = new int[1];
AM(x);

We get a compilation error, something like "invalid arguments", "cannot convert from int[] to object[]".

But, if we have an argument (object y), we can have input int as input parameter.

My question is: why Microsoft design them in different ways?

4

3 に答える 3

9

When you pass an int (a value type) into a method with an object (a reference type) parameter, a new object is created on the heap and the value of the int is copied into it. A reference to the object (the boxed int) is then given passed into the method parameter.

int[] and object[] are both arrays, but they have very different element types. As arrays, they are both reference types, and so a method taking an object[] parameter is expecting a reference to an array of objects. A reference to an array of ints is very different.

Because int is a value type, there's no simple way to turn a reference to int[] into a reference to object[] without iterating over the whole int[] and boxing each element. That could be an expensive operation in terms of time and memory, and the compiler is not going to do it for you automatically.

于 2012-07-27T03:34:48.787 に答える
4

Only arrays of reference types may be assigned to arrays of other reference types (like Object). Since int is a value type, you can't do this.

This is called Array Covariance

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[].

于 2012-07-27T03:36:11.240 に答える
2

An array of objects is a completely different animal when compared to an array of int (as you can see with the cast error you get). However, both object[] and int[] are objects, so you can cast them both to their primal type (as in primitive) which is the object.

于 2012-07-27T03:33:54.040 に答える