[英]VB.net Object Array throwing an exception
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! 任何帮助,将不胜感激!
Try using a list: 尝试使用列表:
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
Your problem is that arrays need a size when they're initialized and setting it to Nothing gives you exactly that. 您的问题是数组在初始化时需要大小,将其设置为Nothing不能完全满足您的要求。 Give the array a size and don't set it to Nothing.
给数组指定一个大小,不要将其设置为Nothing。 Also, there's a much cleaner way to do this.
此外,还有一种更清洁的方法可以执行此操作。
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
You should specify the array size 您应该指定数组大小
Dim i as Integer = dir.GetFiles().count or dir.FilesCount() 将我作为整数= dir.GetFiles()。count或dir.FilesCount()
Dim songsInDir(i) As Song = Nothing 昏暗的歌曲InDir(i)作为歌曲=无
or you can use dynamic array 或者你可以使用动态数组
put this line inside your for loop 将此行放入for循环中
ReDim Preserve songsInDir(i) ReDim保存歌曲InDir(i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.