繁体   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