2011-01-29 61 views
0

我有一個這樣的程序。修改每個循環內部的對象設置所有對象的值最後一個的屬性

Module Module1 

Public Class Mstr 
    Public Property Prop1 As String 
    Public Property Prop2 As String 
    Public Property Prop3 As String 
    Public Property Prop4 As String 

    Public Property lstDtlsA As List(Of DtlsA) 
    Public Property DtlsB As DtlsB 
End Class 


Public Class DtlsA 
    Public Property Prop1 As String 
    Public Property Prop2 As Integer 
    Public Property Prop3 As String 
    Public Property Prop4 As Integer 

    Public Property DtlsB As DtlsB 
End Class 

Public Class DtlsB 
    Public Property Prop1 As String 
    Public Property Prop2 As Integer 
    Public Property Prop3 As String 
    Public Property Prop4 As Integer 
End Class 

Private Sub Process(ByVal mstr As Mstr) 
    Dim lstTemp As New List(Of DtlsA) 

    For Each dtl In mstr.lstDtlsA 
     'Do some processing 
     PopulateDtlsBForDtlsA(mstr, dtl) 
     lstTemp.Add(dtl) 
    Next 

    'Finally set the modified dtls list to mstr 
    mstr.lstDtlsA = lstTemp 
End Sub 

Sub PopulateDtlsBForDtlsA(ByVal mstr As Mstr, ByVal dtl As DtlsA) 
    Dim dtlB As New DtlsB 

    dtlB = mstr.DtlsB 
    dtlB.Prop1 = mstr.Prop1 
    dtlB.Prop2 = dtl.Prop2 
    dtlB.Prop4 = dtl.Prop4 
    dtl.DtlsB = dtlB 
End Sub 

Sub Main() 
    Dim mstr As New Mstr 
    mstr.Prop1 = "Master Property 1" 
    mstr.Prop2 = "Master Property 2" 
    mstr.Prop3 = "Master Property 3" 
    mstr.Prop4 = "Master Property 4" 

    mstr.lstDtlsA = New List(Of DtlsA) 
    Dim dtlA As DtlsA 

    dtlA = New DtlsA 
    dtlA.Prop1 = "Detail A Property 11" 
    dtlA.Prop2 = 12 
    dtlA.Prop3 = "Detail A Property 13" 
    dtlA.Prop4 = 12 
    mstr.lstDtlsA.Add(dtlA) 

    dtlA = New DtlsA 
    dtlA.Prop1 = "Detail A Property 21" 
    dtlA.Prop2 = 22 
    dtlA.Prop3 = "Detail A Property 23" 
    dtlA.Prop4 = 24 
    mstr.lstDtlsA.Add(dtlA) 

    dtlA = New DtlsA 
    dtlA.Prop1 = "Detail A Property 31" 
    dtlA.Prop2 = 32 
    dtlA.Prop3 = "Detail A Property 33" 
    dtlA.Prop4 = 34 
    mstr.lstDtlsA.Add(dtlA) 

    Dim dtlB As New DtlsB 

    dtlB.Prop1 = "Detail B Property 1 set by master" 
    dtlB.Prop3 = "Detail B Property 3 set by master" 
    mstr.DtlsB = dtlB 

    Process(mstr) 
End Sub 

前端模塊

但它不工作,我希望它。您可以從Quickwatch while debugging

中看到它所有三個DtlsA對象的DtlsB屬性都具有上次迭代的值。請讓我知道我在這裏做錯了什麼,對這個概念的一些解釋也會非常有幫助。謝謝!!!

回答

0

要重複使用,在這裏突變相同的對象:

dtlB = mstr.DtlsB 

而不是使用現有的對象創建一個完全新的對象,或將現有一個的克隆。

相關問題