[英]C#: Array.CreateInstance: Unable to cast object of type [*] to type []
我想通過調用在c#中創建一個非零下界一維數組
Array.CreateInstance(typeof(int), new int[] { length }, new int[] { lower });
返回數組的類型不是int [],而是int [*]。 任何人都可以詳細說明這是什么意思? 我希望能夠將此數組返回給調用者,例如,
int[] GetArray() { ... }
謝謝。
是的,這是一個難題!
矢量和一維數組之間存在差異。 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[*]
我無法找到要驗證的實際代碼,但是試驗該語法似乎表明具有非零基礎的一維數組。
這是我的結果:
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[,]"
如果你需要的只是一維數組,那么應該這樣做
Array.CreateInstance(typeof(int), length)
指定lowerBound時,如果完全不同則返回類型
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.