2011-10-03 42 views
0

我想通過一個字節數組循環,並將內容複製到一個新的字節列表,並將其顯示回來。請參閱下面的代碼。追加字節把空間

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    Dim myByte() As Byte = New Byte() {65, 66, 67} 
    Dim newByte() As Byte = New Byte() {} 
    Dim tempByteList As New List(Of Byte) 
    For i As Integer = 0 To 2 
     ReDim newByte(1) 
     Array.Copy(myByte, i, newByte, 0, 1) 
     tempByteList.AddRange(newByte) 
    Next 
    Dim str1 As String = System.Text.UnicodeEncoding.UTF8.GetString(tempByteList.ToArray()) 
End Sub 

我希望看到STR1爲「ABC」,但放了我得到的是「ABC」(即字母之間的空格) 請注意:我有一個循環內的複製(塊),並得到結果在最後,這只是一個樣本來重現我的真實問題。

任何幫助將不勝感激

+0

爲什麼這個標籤C# –

+0

@ChristopherCurrens:刪去了 –

回答

1

的問題是在你的ReDim聲明。 Microsoft's definition of ReDim指出,指定的數組邊界總是從0到指定的邊界(在你的案例1中),所以你基本上是ReDim -ing 2項數組,這就是爲什麼你看到A,B之間的「空格」 ,和C元素。更改ReDim語句

ReDim newByte(0) 

,所有應該很好,你將被宣佈newByte陣列從0轉到0(單個項目陣列),這是你想要的。

+0

感謝史蒂夫,我只是想通了這一點,當你回答這再次向我保證! – melspring

0

您也可以使用VB.Net中的Array.CreateInstance方法,而不需要執行redim,因爲createInstance使其與您指定的大小完全相同。 (只有其他的東西是你需要建立你的TempByteList還是你在循環開始時知道你需要的大小,因爲你可以最初創建你的最終字節數組並將其Array.Copy到正確的偏移量而不是附加到名單,然後.ToArray()

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 
    Dim myByte() As Byte = New Byte() {65, 66, 67} 
    Dim newByte() As Byte = CType(Array.CreateInstance(GetType(Byte), 1), Byte()) 
    Dim tempByteList As New List(Of Byte) 
    For i As Integer = 0 To 2 
     Array.Copy(myByte, i, newByte, 0, 1) 
     tempByteList.AddRange(newByte) 
    Next 
    Dim str1 As String = System.Text.UnicodeEncoding.UTF8.GetString(tempByteList.ToArray()) 
End Sub