将成员添加到列表中覆盖先前的成员

时间:2019-03-06 07:06:08

标签: vb.net

我需要从Excel文件中读取狗的出生日期列表,并将其存储在列表中。读取效果很好,每当我向列表中添加一条新狗时,列表数量都会增加。到目前为止,一切都很好。

问题是,当我添加第二条记录时,第一条记录被第一条记录内容替换,因此我有两条相同的记录。以此类推,每条新记录都如此。最后,我有很多相同的记录-都有最后一只狗的价值。

狗类是:

Public Class DogClass
    Public Name As String
    Public Dob As Date
    Public Age As Integer
    Public Sex As String

    Public Sub setDogName(ByVal _name As String)
        Name = _name
    End Sub
    Public Sub setDogDOB(ByVal _dob As Date)
        Dob = _dob
    End Sub
    Public Sub setDogAge(ByVal _age As String)
        Age = _age
    End Sub
    Public Sub setDogSex(ByVal _sex As String)
        Sex = _sex
    End Sub

End Class

列表的类别为:

Public Class DogsListClass
    Public dogsList As New List(Of DogClass)

    Public Function DodgsCnt() As Integer
        DodgsCnt = dogsList.Count()
    End Function

    Public Function DogExsists(_dogName As String) As Boolean
        Dim res As Boolean = False
        For Each item As DogClass In dogsList
            If item.Name = _dogName Then
                res = True
            End If
        Next
        Return res
    End Function
    Public Sub AddDog(_dog As DogClass)
        dogsList.Add(_dog)
    End Sub

End Class

呼叫:

Dim tdog As New DogClass
Dim DogsList As New DogsListClass
Do
    tdog.setDogName(MyExcel.Cells(row_cnt, col_cnt).text)
    tdog.setDogDOB(MyExcel.Cells(row_cnt, col_cnt + 1).value)
    DogsList.AddDog(tdog)
Loop

您知道为什么要覆盖记录吗?

1 个答案:

答案 0 :(得分:0)

DogsList变量必须在Do ... Loop外部声明,否则,您将在每次迭代时创建一个“ New” DogsList,并且根据此代码,您最终应该在集合中只有一个项目,而不是很多。 另外,在循环中声明DogsList可以防止您在代码的其余部分之外使用它。