0

我尝试获取每张专辑的歌曲列表。我创建了 2 个类:专辑和歌曲,所以我可以将它们组织如下:

Public Class Album
    Sub New()
        Entered = Now
    End Sub
    Public Entered As DateTime
    Public AlbumName As String = ""
    Public Artist As String = ""
    Public YearReleased As Integer = 1900
    Public Songs As New List(Of Song)
End Class

Public Class Song
    Public SongName As String = ""
    Public SongLength As String = ""
End Class

但是,当我将歌曲添加到专辑时,我总是得到最后一首输入的歌曲。这是一个输出结果的例子。

Protected Sub Test()
    Dim vAlbum As New Album
    Dim vsong As New Song

    vAlbum.AlbumName = "Test 01"
    vAlbum.Artist = "Jackie"
    vAlbum.YearReleased = 2012

    vsong.SongName = "Exit"
    vsong.SongLength = "1.5"
    vAlbum.Songs.Add(vsong)

    vsong.SongName = "Exit II"
    vsong.SongLength = "2.5"
    vAlbum.Songs.Add(vsong)

    For Each sSong As Song In vAlbum.Songs
        Response.Write(sSong.SongName + "<br>")
    Next
End Sub

输出 :

  • 出口二
  • 出口二
  • 我到处都有谷歌,但找不到所有歌曲的最新记录。

    欢迎任何帮助。

    谢谢,弗雷德

    4

    2 回答 2

    2

    经典参考问题。您的 vsong 始终是同一个对象。您需要实例化一个新实例:

    ...
    vAlbum.Songs.Add(vsong)
    vsong = new Song()
    vsong.SongName = "Exit II"
    ...
    
    于 2012-09-12T09:49:56.760 回答
    1

    您添加了Song两次相同的内容,只是更改了它的字段。

    你应该使用这样的东西:

    Dim vAlbum As New Album
    
    vAlbum.AlbumName = "Test 01"
    vAlbum.Artist = "Jackie"
    vAlbum.YearReleased = 2012
    
    Dim vsong As New Song
    vsong.SongName = "Exit"
    vsong.SongLength = "1.5"
    vAlbum.Songs.Add(vsong)
    
    vsong As New Song ' create a new instance of Song
    vsong.SongName = "Exit II"
    vsong.SongLength = "2.5"
    vAlbum.Songs.Add(vsong)
    

    或者更好的是,使用对象初始化器或创建一个接受所有必要值的构造器:

    Public Class Song
    
        Public SongName As String = ""
        Public SongLength As String = ""
    
        Public Sub new(name as String, length as String)
            SongName = name
            SongLength = length
        End Sub
    
    End Class
    
    ...
    
    vAlbum.Songs.Add(new Song("Exit", "1.5"))
    vAlbum.Songs.Add(new Song("Exit II", "2.5"))
    
    于 2012-09-12T09:49:10.477 回答