No se puede convertir una matriz de tipo de valor en un objeto params []

If C# can cast an int to an object, why not an int[] to an object[]?

Simple Program Example:

void Main()
{
    var a = new String[]{"0", "1"};
    var b = new int[]{0, 1};

    AssertMoreThan1(a); // No Exception
    AssertMoreThan1(b); // Exception
}

static void AssertMoreThan1(params object[] v){
    if(v.Length == 1){
        throw new Exception("Too Few Parameters");
    }
}

preguntado el 01 de febrero de 12 a las 22:02

2 Respuestas

If C# can cast an int to an object, why not an int[] to an object[]?

Your question could be also stated as "what are the covarianza rules for array conversions in C#?"

They are a bit tricky, and broken in several interesting and unfortunate ways.

First off, we should clearly state what we mean by "covariance". Covariance is the property that a cartografía preserves a relación. The mapping here is "T goes to array of T". The relación is "can be implicitly converted". For example:

Giraffe se puede convertir implícitamente a Mammal.

That's a relationship between two types. Now apply the mapping to both sides of the relationship:

Giraffe[] se puede convertir a Mammal[].

If the truth of the first statement always entails the truth of the second statement -- that is, if the mapping conservas the truth of the relationship -- then the mapping is said to be "covariant".

As a shorthand, instead of saying "the mapping from T to array of T is a covariant mapping over the implicit conversion relation", we just say "arrays are covariant" and hope that the rest of that is understood from context.

OK, now that we have the definition down: Arrays with reference type elements are covariant in C#. Tragically, this is broken covariance:

class Mammal {}
class Giraffe : Mammal {}
class Tiger : Mammal {}
...
Mammal[] mammals = new Giraffe[1];  

This is perfectly legal because arrays of reference type elements are covariant in C#. But then this crashes at runtime:

mammals[0] = new Tiger();

because mammals is really an array of Giraffes.

This means that every time you escribir to an array whose elements are unsealed reference types, the runtime performs a type check and might crash if the type check fails.

This is my candidate for "worst feature of C#", but it does in fact trabajo.

Your question is "why does array covariance not work when the source array is an array of value type and the target array is an array of reference type?"

Porque those two things have a different form at runtime. Suponga que tiene un byte[] with ten elements. The actual storage reserved for the array elements is ten bytes long. Suppose you are on a 64 bit machine and you have an object[] with ten elements. The storage is eight times bigger!

Clearly you cannot convert via reference conversion a reference to storage for ten bytes to storage for ten eight-byte references to bytes. The extra seventy bytes don't come out of nowhere; someone has to allocate them.

Además: who does the boxing? If you have an array of ten objects and each object is a byte, each one of those bytes is en caja. But bytes in a byte array are not boxed. So when you do the conversion, who does the boxing?

In general in C#, covariant conversions always preserve representation. The representation of a "reference to Animal" is exactly the same as the representation of "reference to Giraffe". But the representations of "int" and "reference to object" are completely different.

One expects that casting one array type to another does not allocate and copy a huge array. But we cannot have identidad referencial between an array of ten bytes and an array of eighty bytes containing ten references, and therefore the entire thing is simply made illegal.

Now, you might then say, well, what happens when the representations son lo mismo for value types? In fact, this is illegal in C#:

int[] x = new uint[10];

because in C# the rule is that only covariant array conversions involving only reference types are legal. But if you force it to be done by the runtime:

int[] x = (int[])(object) new uint[10];

Then the runtime allows it because a four byte int and a four byte uint have the same representation.

If you want to understand this better then you should probably read my entire series of articles on how covariance and contravariance works in C#:

Respondido 02 Feb 12, 20:02

When I had to scroll more than once, I already knew whose face would be at the bottom :) - Marc Gravell

@MarcGravell Mammal/Giraffe/Tiger gives it away every time. - asawyer

Thanks for the explanation Eric! I'm an avid reader of your blog. I'll have to read and re-read your answer a few times before I truly "get it". - Daryl

Take note that, as Eric warns in "The specifics of unsafe reference-element array covariance", C#'s array covariance feature is broken. If you have legitimate need for covariance but want to be protected by C#'s type-safety system, use IEnumerable<T> in .Net 4.0+. - Brian

It's only taken me two months, but I finally understand why it doesn't work! - Daryl

Indeed, you cannot convert that. Reference-type arrays are covariant; value-type arrays no son. So; you will have to use one of:

an array of boxed values:

var b = new object[] {0,1};

o tu podría utilizado IList:

static void AssertMoreThan1(IList v) {
   ... (check with .Count)
}

or generics:

static void AssertMoreThan1<T>(T[] v) {
   ...
}

The last one would be my preference.

Respondido 02 Feb 12, 02:02

+1 value-type arrays cannot be cast implicitly. You can use Linq and do the following b.Cast<object>().ToArray() - Daniel Moisés

In this case Marc, I really do want the function defined with params because I primarily use it with the standard comma delimited parameter method of calling it. (and I made the AssertMoreThan1 function up for the purpose of this post, just as the simplest example of the problem I was experiencing) I did end up using your first suggestion to solve my current issue, but I was more interested in the why, (which of course Mr. Lippert has answered with extreme thoroughness) - Daryl

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.