2012-08-22 14 views
10

我想創建一個非零下界在c#一個維陣列通過調用C#:Array.CreateInstance:無法轉換類型的對象[*]輸入[]

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

的類型來對返回的數組不是int [],而是int [*]。任何人都可以詳細說明這是什麼意思?我希望能夠將此數組返回給調用者,例如,

int[] GetArray() { ... } 

謝謝。

+0

在哪裏出現了'INT [*]'?當我運行該代碼時,我得到一個「int」數組。 –

+0

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

+1

任何原因你不想使用'new int [長度]'?它更短,人們使用的標準語法,並且工作... – Servy

回答

12

是的,這是一個疑難雜症!

載體和一維數組之間是有區別的。 int[]載體。載體(如int[]必須是基於0的。否則,您必須將其稱爲Array。例如:

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

或(注意,這仍然是零基礎):

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

如果陣列不能爲0爲主,那就對不起:你必須使用Array,不int[]

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

爲了使它更加混亂,有之間的差異:

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

我找不到要驗證的實際代碼,但試驗該語法似乎指示具有非零基的一維數組。

這裏是我的結果:

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

如果你需要的是一維數組,比這應該做的伎倆

Array.CreateInstance(typeof(int), length) 

如果指定下界,然後返回類型,如果完全不同

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 
相關問題