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)
... sub 设置变量并检索文件信息(此代码有效)
任何帮助将不胜感激!
I am getting an exception when running the following code.
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
I get an error on line:
songsInDir(i) = New Song(file.Name)
I get an uncaught exception that says:
"Object reference not set to an instance of an object."
The song object has a:
Public Sub new(By Val filename as String)
... sub that sets a variable and retrieves file info (this code works)
Any help would be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用列表:
Try using a list:
您的问题是数组在初始化时需要一个大小,并将其设置为 Nothing 可以准确地满足您的要求。为数组指定一个大小,不要将其设置为 Nothing。此外,还有一种更简洁的方法可以做到这一点。
Your problem is that arrays need a size when they're initialized and setting it to Nothing gives you exactly that. Give the array a size and don't set it to Nothing. Also, there's a much cleaner way to do this.
您应该将数组大小
Dim i 指定为 Integer = dir.GetFiles().count 或 dir.FilesCount()
DimongsInDir(i) As Song = Nothing
或者您可以使用动态数组
将此行放入 for 循环中
ReDim PreserveongsInDir(我)
You should specify the array size
Dim i as Integer = dir.GetFiles().count or dir.FilesCount()
Dim songsInDir(i) As Song = Nothing
or you can use dynamic array
put this line inside your for loop
ReDim Preserve songsInDir(i)