VB.net Object Array抛出异常

时间:2012-02-24 23:03:50

标签: vb.net arrays class object constructor

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

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)

... sub设置变量并检索文件信息(此代码有效)

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:2)

尝试使用列表:

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

答案 1 :(得分:0)

你的问题是,数组在初始化时需要一个大小,并将其设置为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 

答案 2 :(得分:-1)

您应该指定数组大小

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

Dim songsInDir(i)As Song = Nothing

或者您可以使用动态数组

将此行放入for循环

ReDim Preserve songsInDir(i)