List(Of String)的内容未保存

时间:2017-12-28 15:23:28

标签: vb.net class

我试图解析如下的段落......

Group 1.  Does this or does that. Or Sometimes this. Or that.  

Group 2.  I do lots of things. But not this. Or that.

Group 3.  I do this. I do that. Sometimes this. Sometimes that.

“组1-3”是组织名称,并且由句点分隔的每个后续句子是函数。

代码:

Public Sub parseParagraphs(paragraphList As List(Of String))
    Dim listOfOrgs As New List(Of EAB_Org)
    Dim listOfFuntions As New List(Of String)

    Dim orgName As String

    For Each item In paragraphList
        listOfFuntions.Clear()
        Dim words As String() = item.Split(New Char() {"."c}) 'Splits on periods
        orgName = words(0) 'Sets the orgName
        For index As Integer = 1 To words.Count - 1 'rest of items in list are functions performed
            listOfFuntions.Add(words(index))
        Next
        Dim anOrg As New EAB_Org(orgName, listOfFuntions)

        listOfOrgs.Add(anOrg)
    Next
End Sub

EAB课程:

Public Class EAB_Org
    Dim orgName As String
    Dim listOfTasks As List(Of String)

    Public Sub New(theOrgName As String, theListOfTasks As List(Of String))
        orgName = theOrgName
        listOfTasks = theListOfTasks
    End Sub

    Public Function getOrgName()
        Return orgName
    End Function

    Public Function getListOfTasks()
        Return listOfTasks
    End Function
End Class

出于某种原因,当我打印出listOfOrgs的内容时,所有组织名称都是正确的,但功能都是相同的,并且总是读入最后一组功能。

我用来打印的代码:

Public Sub writeExcel(listOfOrgs As List(Of EAB_Org))
    For Each anItem In listOfOrgs
        Console.WriteLine(anItem.getOrgName)
        For Each anotherItem In anItem.getListOfTasks
            Console.WriteLine(anotherItem)
        Next
    Next

End Sub

输出看起来像:

Group 1
I do this. I do that. Sometimes this. Sometimes that.

Group 2
I do this. I do that. Sometimes this. Sometimes that.

Group 3
I do this. I do that. Sometimes this. Sometimes that.

1 个答案:

答案 0 :(得分:2)

问题在于,在EAB_Org的构造函数中,listOfFuntions只是parseParagraphs Sub中指向theListOfTasks(您一直在修改)的指针。在构造函数中,您需要创建一个新的List(Of String)并将Public Sub New(theOrgName As String, theListOfTasks As List(Of String)) orgName = theOrgName listOfTasks = New List(Of String) For Each item As String In theListOfTasks listOfTasks.Add(item) Next End Sub 中的值复制到其中。

将构造函数更改为以下内容:

$cars = array (
 array("name"=>"jeep","Year"=>"2012"),
 array("name"=>"ferrari","Year"=>"2017"),  
 array("name"=>"jaguar","Year"=>"2013")
);

foreach ($cars as $value) {

  if($value[Year] == 2013){
    echo $value[name] ."<br>";
    }
}