簡體   English   中英

無法將類型為“ WhereSelectArrayIterator`2 [System.String,System.Byte]”的對象強制轉換為“ System.Byte []”。 Vb.net

[英]Unable to cast object of type 'WhereSelectArrayIterator`2[System.String,System.Byte]' to type 'System.Byte[]'. Vb.net

我正在嘗試在vb.net中創建一個程序,它的作用是當您打開文件時將打開的文件轉換為十六進制代碼,但是問題是當它保存並嘗試將其轉換回正常狀態時。 結果為:(無法將類型為“ WhereSelectArrayIterator`2 [System.String,System.Byte]”的對象強制轉換為“ System.Byte []”。)

這是打開和保存代碼

打開文件代碼:FillWithHex(RichTextBox1,OpenFileDialog1.FileName)

    Async Sub FillWithHex(rtb As RichTextBox, name As String)
    For Each ctl In Controls
        ctl.Enabled = False
    Next ctl
    Dim buff(1000000) As Byte

    Using fs = New FileStream(name, FileMode.Open)
        Using br = New BinaryReader(fs)
            While True
                Dim text = String.Empty
                buff = br.ReadBytes(1000000)
                Await Task.Run(Sub() text = String.Join(" ", buff.
                            Select(Function(b) b.ToString("X2")))).
                            ConfigureAwait(True)
                rtb.AppendText(text)
                If buff.Length < 1000000 Then
                    Exit While
                End If
            End While

        End Using
    End Using
    For Each ctl In Controls
        ctl.Enabled = True
    Next ctl
    ToolStripLabel1.Text = "Status: Idle"
End Sub

這是保存代碼

        Try
        Dim b As Byte() = RichTextBox1.Text.Split(" "c).Select(Function(n) Convert.ToByte(Convert.ToInt32(n, 16)))
        My.Computer.FileSystem.WriteAllBytes(SaveFileDialog1.FileName, b, False)
    Catch ex1 As Exception
        Try
            Dim b As Byte() = RichTextBox1.Text.Split(" "c).Select(Function(n) Convert.ToByte(Convert.ToInt32(n, 16)))
            My.Computer.FileSystem.WriteAllBytes(OpenFileDialog1.FileName, b, False)
        Catch ex As Exception
            MsgBox("Exception caught : " + vbNewLine + vbNewLine + ex.ToString, MsgBoxStyle.Critical, "Exception Error")
    End Try
    End Try

您對IEnumerable(Of T)類型的對象調用的Enumerable類的擴展方法IEnumerable(Of T)Select方法)通常不返回數組。 它們通常返回實現IEnumerable(Of T)某種類型。 特定類型通常無關緊要。 如果需要數組,則需要在該對象上調用ToArray ToList將類似地創建一個List(Of T) 這意味着您需要:

Dim b = RichTextBox1.Text.
                     Split(" "c).
                     Select(Function(n) Convert.ToByte(n, 16)).
                     ToArray()

請注意,我刪除了顯式類型聲明,即As Byte() ,然后推斷類型。 這樣可以使代碼更整潔,但是如果您認為使用顯式類型會有所幫助,則不必這樣做。 請注意,我還刪除了無用的Convert.ToInt32調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM