2012-10-20 39 views
0

我想將System.Array類型的數組轉換爲Double()Double(,)(我已經知道哪一個要轉換爲)。有問題的代碼行遵循在VB.NET 2012中將System.Array轉換爲Double()

Dim kernel As Double() = CType(Array.CreateInstance(GetType(Double), _ 
    {2 * limit + 1}, {-limit}), Double()) 

limit被預定義爲一個有效的,積極的Integer。我得到了InvalidCastException。我如何去做這件事?或者用< 0開始索引創建Double數組的另一種方法?

回答

0

可以使用Enumerable.Range方法來創建一個一維數組,像這樣:

Dim start = 0 
Dim count = 10 

Dim singleArray = Enumerable.Range(start, count).ToArray() 

要創建一個多維數組,你必須創建自己的擴展方法來修改該集合,因爲我已經在下面做

Public Module Extensions 
    <Runtime.CompilerServices.Extension()> 
    Function SelectMultiDimension(Of T)(collection As IEnumerable(Of T), rows As Integer, cols As Integer) As T(,) 
     Dim multiDimArray(rows - 1, cols - 1) As T 
     Dim i As Integer = 0 

     For Each item In collection 
      If i >= multiDimArray.Length Then Exit For 

      multiDimArray(i \ cols, i Mod cols) = item 

      i += 1 
     Next 

     Return multiDimArray 
    End Function 
End Module 

然後你就可以使用這種方式:

Dim mArray = Enumerable.Range(start, count).SelectMultiDimension(3, 4) 
+0

第I墨水你誤會了我的問題,我需要一個'Double()'或'Double(,)'數據類型的數組,而不是'Array'數據類型。 ['Array.CreateInstance'方法](http://msdn.microsoft.com/zh-cn/library/x836773a.aspx)已經完成了所有描述。我需要這樣做才能實現與其他API的互操作性。 –