2012-08-22 13 views
10

Voglio creare un non pari a zero limite inferiore una matrice bidimensionale in C# chiamandoC#: Array.CreateInstance: Impossibile eseguire il cast oggetto di tipo [*] per digitare []

Array.CreateInstance(typeof(int), new int[] { length }, new int[] { lower }); 

Il tipo del restituita array non è int [], ma int [*]. Qualcuno può approfondire cosa significa? Voglio essere in grado di restituire questo array al chiamante, ad esempio,

int[] GetArray() { ... } 

Grazie.

+0

Dove stai vedendo 'int [*] '? Quando eseguo quel codice ottengo un array di 'int's. –

+0

D Stanley, in Array.CreateInstance (typeof (int), new int [] {6}, new int [] {6}). GetType(). FullName –

+1

Qualsiasi motivo per cui non si desidera utilizzare 'new int [ lunghezza] '? È più breve, le persone della sintassi standard usano e lavora ... – Servy

risposta

12

Sì, questo è un Gotcha!

C'è una differenza tra un vettore e un array monodimensionale. Un int[] è un vettore . Un vettore (come un int[]) deve essere a base 0. Altrimenti, devi chiamarlo Array. Per esempio:

// and yes, this is doing it the hard way, to show a point... 
int[] arr1 = (int[]) Array.CreateInstance(typeof(int), length); 

o (notare che questo è ancora a base zero):

int[] arr2 = (int[]) Array.CreateInstance(typeof (int), 
     new int[] {length}, new int[] {0}); 

Se l'array non può essere 0-based, quindi mi dispiace: devi usare Array, non int[]:

Array arr3 = Array.CreateInstance(typeof(int), 
     new int[] { length }, new int[] { lower }); 

Per rendere ancora più confusa, c'è una differenza tra:

typeof(int).MakeArrayType() // a vector, aka int[] 
typeof(int).MakeArrayType(1) // a 1-d array, **not** a vector, aka int[*] 
2

Non riesco a trovare il codice effettivo da verificare, ma sperimentando che la sintassi sembra indicare un array unidimensionale con una base diversa da zero.

Ecco i miei risultati:

0-Based 1-D Array :  "System.Int32[]" 
Non-0-based 1-D Array:  "System.Int32[*]" 
0-based 2-D Array :  "System.Int32[,]" 
Non-0-based 2-D Array : "System.Int32[,]" 
2

Se tutto ciò che serve è array monodimensionale, che questo dovrebbe fare il trucco

Array.CreateInstance(typeof(int), length) 

Quando si specifica lowerbound, tipo poi tornare se molto diverso

var simpleArrayType = typeof(int[]); 

var arrayType = Array.CreateInstance(typeof(int), 10).GetType(); 
var arrayWithLowerSpecifiedType = Array.CreateInstance(typeof(int), 10, 5).GetType(); 

Console.WriteLine (arrayType == simpleArrayType); //True 
Console.WriteLine (arrayWithLowerSpecifiedType == simpleArrayType); //False 
Problemi correlati