1

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

    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

提前致谢!

4

1 回答 1

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 类的新实例并将引用分配给在开始时声明的相同变量

于 2013-04-19T20:23:11.147 回答