VB / CLASS问题:只显示所有记录的最后一条记录

时间:2012-09-12 09:45:12

标签: vb.net

我试着获得每张专辑的歌曲列表。我创建了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

输出:

  • 退出II
  • 退出II
  • 我到处都是谷歌,但找不到onyl,所有歌曲的最新记录都显示出来。

    欢迎任何帮助。

    谢谢,弗雷德

    2 个答案:

    答案 0 :(得分:2)

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

    ...
    vAlbum.Songs.Add(vsong)
    vsong = new Song()
    vsong.SongName = "Exit II"
    ...
    

    答案 1 :(得分: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"))