I'm trying to populate one list from another. I would think this code should work, but at the end of the day I get a list of identical items.
Public Sub WriteDatFile(ByRef lstReasons As System.Collections.Generic.List(Of LetterReason))
Dim tmplstReason As New TCPService.LetterReason
Dim tmplstReasons As New System.Collections.Generic.List(Of TCPService.LetterReason)
'Load the letter reasons
For Each LetterReason In lstReasons
tmplstReason._reas开发者_如何转开发on = LetterReason.Reason
tmplstReasons.Add(tmplstReason)
Next
RetVal = .......
End Sub
Now, when I set a breakpoint and check from the calling WCF I get this:
lstReason(0).Reason = One
lstReason(1).Reason = Two
lstReason(2).Reason = Three
But, when I set a breakpoint (after the load) in this subroutine I get the following output:
tmplstReason(0)._reason = Three
tmplstReason(0)._reason = Three
tmplstReason(0)._reason = Three
What's going on??? Any ideas?
Thanks, Jason
You need to create a new instance of LetterReason
inside the loop and add the new instance to the list. Try this
For Each LetterReason In lstReasons
Dim tmplstReason As New TCPService.LetterReason
tmplstReason._reason = LetterReason.Reason
tmplstReasons.Add(tmplstReason)
Next
tmplstReason._reason = LetterReason.Reason
tmplstReasons.Add(tmplstReason)
Look carefully. You're not actually changing tmplstReason, you're changing the ._reason property of it. You then add tmplstReason to the list 3 times.
The result is that you actually add the same thing to the list each time, and change that one object's ._reason variable each time. Since they're all the same, they all have the same value. :)
精彩评论