使用对象列表解析文本文件

时间:2013-04-19 20:20:44

标签: vb.net parsing streamreader

我正在尝试解析一个包含多个贷款的.txt文件。我的逻辑是:我创建一个包含我需要的属性的Loan类,我创建了一个贷款对象列表。我创建一个新的贷款对象并将其添加到列表中。然后我读完了txt文件并填充了对象属性。当我到达文件的末尾时,我需要创建一个新的贷款对象并重新开始,因为该文件中有多个贷款,我需要每个贷款一个对象。问题是当我使用下面的代码时,我得到了错误"局部变量' myLoans'将变量隐藏在封闭块中#34;有一个更好的方法吗?

    Public Class Loan
        Public Property LoanId As String
        Public Property LoanProvider As String
    End Class

    Dim listOfLoans As New List(Of Loan)()
    Dim myLoans As New Loan
    listOfLoans.Add(myLoans)

    Dim line As String
    Using r As New StreamReader("c:text.txt")
        line = r.ReadLine()
        Do While (Not line Is Nothing)
            If (line.Substring(0, 10) = "Loan id:") Then
                myLoans.LoanId = line.Substring(10, line.Length - 10).Trim()

            ElseIf (line.Substring(0, 14) = "Loan Provider:") Then
                myLoans.LoanProvider = line.Substring(14, line.Length - 19).Trim()

            ElseIf (line.Substring(0, 30) = "Last line of file:") Then
                Dim myLoans As New Loan
                listOfLoans.Add(myLoans)

            End If
            line = r.ReadLine
        Loop
    End Using

提前致谢!

1 个答案:

答案 0 :(得分:0)

在这些行中,您将创建类Loan的新实例,并将此新实例分配给使用外部变量名称调用的其他变量。
当然,这个变量的生命周期仅限于封闭的ElseIf / End IF块,与第一个无关。只是名称和编译器警告你陷阱

ElseIf (line.Substring(0, 30) = "Last line of file:") Then
    Dim myLoans As New Loan
    listOfLoans.Add(myLoans)
End If

您只需更改

中的行
ElseIf (line.Substring(0, 30) = "Last line of file:") Then
    myLoans = New Loan    'no Dim so the myLoans is the external one'
    listOfLoans.Add(myLoans)
End If

这将创建一个Loan类的新实例,并将引用分配给在开始时声明的同一个变量