簡體   English   中英

無法將類型為'System.Byte []'的對象強制轉換為'System.IConvertible'

[英]Unable to cast object of type 'System.Byte[]' to type 'System.IConvertible'

我在下面的代碼中得到錯誤

Function ReadFile(ByVal sPath As String) As Byte

    Dim data As Byte
    data = Nothing

    Dim fInfo As FileInfo
    fInfo = New FileInfo(sPath)

    Dim numBytes As Long
    numBytes = fInfo.Length

    Dim fStream As FileStream
    fStream = New FileStream(sPath, FileMode.Open, FileAccess.Read)

    Dim br As BinaryReader
    br = New BinaryReader(fStream)

    data = Convert.ToByte(br.ReadBytes(numBytes)) `getting error on this line`
    Return data
End Function

ReadBytes函數返回一個字節數組,您將其傳遞給Convert.ToByte函數,該函數在運行時拋出異常,因為您無法將多個字節的數組轉換為單個字節。 根據您要完成的操作,解決問題的操作會有所不同。

  • 您已定義ReadFile以返回單個字節,如字節中所示。
  • ReadBytes返回一個字節數組,如Byte()。
  • 您不能將Byte()轉換為Byte。
    • 字節(0)=字節
    • 字節<>字節()
  • Convert.ToByte接受一個Object。
  • 帶有Option Strict Off的Visual Basic .NET將嘗試通過調用Byte()數組上的System.IConvertible接口將Byte(),即傳遞給Convert.ToByte的Object轉換為Byte,這將因為一個數組而拋出異常沒有實現這個接口。

從您的函數實現中,很明顯您想要返回所有字節。 因此,更改ReadFile以返回Byte()並刪除ToByte方法調用。

暫無
暫無

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

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