2012-02-24 73 views
2

運行以下代碼時出現異常。VB.net對象數組拋出異常

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) 

...子,設置一個變量,並獲取文件信息(此代碼)

任何幫助,將不勝感激!

回答

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 
+0

這是最好的解決方案。非常感謝! – 2012-02-24 23:39:22

-1

應指定數組大小

昏暗i設定爲整數= dir.GetFiles()。計數或dir.FilesCount()

昏暗songsInDir(I)的樂曲=無

或您可以使用動態數組

,就把這行你在for循環

使用ReDim保留songsInDir(I)

+0

我不知道爲什麼有人爲我的答案VoteDown?雖然它是正確的! – 2012-02-24 23:26:06

+1

ReDim Preserve不是一個好方法,因爲每次重新分配陣列時都會浪費資源。 – 2012-02-24 23:37:01

+0

這是替代解決方案,我爲他提供了兩個。 – 2012-02-24 23:44:46

0

你的問題是,數組需要一個規模時,他們正在初始化,將其設置爲沒有給你這一點。給數組一個大小,不要將它設置爲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