2011-10-03 68 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