【问题标题】:VB.net Object Array throwing an exceptionVB.net 对象数组抛出异常
【发布时间】:2012-02-24 23:03:49
【问题描述】:

运行以下代码时出现异常。

Public Function getSongs() As Song()
   ' Dim dir As New DirectoryInfo(Application.ExecutablePath)
     Dim dir As New DirectoryInfo(directory)
     Dim songsInDir() As Song = Nothing
     Dim i As Integer = 0
     For Each file As FileInfo In dir.GetFiles()
        'only read ".mp3" files
        If file.Extension = ".mp3" Then
            songsInDir(i) = New Song(file.Name)
            i = +i
        End If
    Next
    Return songsInDir
End Function

我在网上遇到错误:

songsInDir(i) = New Song(file.Name)

我得到一个未捕获的异常,它说:

“对象引用未设置为对象的实例。”

歌曲对象有一个:

Public Sub new(By Val filename as String)

... 设置变量并检索文件信息的子程序(此代码有效)

任何帮助将不胜感激!

【问题讨论】:

    标签: vb.net arrays class object constructor


    【解决方案1】:

    尝试使用列表:

    Public Function getSongs() As Song()
      Dim dir As New DirectoryInfo(directory)
      Dim songsInDir() As New List(of Song)
      For Each file As FileInfo In dir.GetFiles()
        'only read ".mp3" files
        If file.Extension = ".mp3" Then
          songsInDir.Add(New Song(file.Name)
        End If
      Next
      Return songsInDir.ToArray()
    End Function
    

    【讨论】:

    • 这是最好的解决方案。非常感谢!
    【解决方案2】:

    您的问题是数组在初始化时需要一个大小,并将其设置为 Nothing 可以让您完全做到这一点。给数组一个大小,不要将其设置为 Nothing。此外,还有一种更清洁的方法。

    Public Function getSongs() As Song()
        Dim songFiles As String() = Directory.GetFiles(directory, "*.mp3")
        Dim songsInDir(songFiles.Length) As Song
        Dim i As Integer = 0
        For Each file As String In songFiles
            songsInDir(i) = New Song(Path.GetFileName(file))
            i = +i
        Next
        Return songsInDir
    End Function 
    

    【讨论】:

      【解决方案3】:

      你应该指定数组大小

      Dim i as Integer = dir.GetFiles().count 或 dir.FilesCount()

      Dim songInDir(i) As Song = Nothing

      或者你可以使用动态数组

      将这一行放在你的 for 循环中

      ReDim Preserve songInDir(i)

      【讨论】:

      • 我不知道为什么有人投票支持我的答案?虽然它是正确的!
      • ReDim Preserve 不是一个好方法,因为每次重新分配数组都会浪费资源。
      • 这是替代解决方案,我为他提供了两个。!!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多